1.创建子进程
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#define E_MSG(str, value) do{perror(str); return (value);} while(0)
int main(void){
printf("getpid: %d\n", getpid());
pid_t pid;
pid = fork();
if(pid == -1) E_MSG("fork", -1);
if(pid == 0){ //子进程运行的代码
printf("create child process OK\n pid = %d\n", getpid());
printf("get parent pid %d\n", getppid());
}
else{ //父进程运行的代码
printf("Run parent process code\n");
printf("getpid: %d\n", getpid());
}
printf("Both run here\n");
return 0;
}
运行结果:
zhongjun@eclipse:~/projects$ ./pr
getpid: 2345
Run parent process code
getpid: 2345
Both run here
create child process OK
pid = 2346
get parent pid 2345
Both run here
2.进程终止
exit(int status)
------
echo $? //查看退出码
3.遗言函数,注册多次,运行多次。注册顺序和调用顺序相反。子进程继承父进程的遗言函数。
#include<stdio.h>
#include<stdlib.h>
void last(void){
printf("last function");
return;
}
int main(void){
atexit(last);
getchar();
return 0;
}
on_exit
调用方法
#include<stdio.h>
#include<stdlib.h>
void bye(int n, void *arg){
printf("bye...%d...%s\n", n, (char *)arg);
return;
}
int main(void){
on_exit(bye, "goodbye...");
getchar();
return 0;
}
- 进程同步
wait
调用及信号。在该方法中,可以再bash
终端运行kill -signal pid
去测试
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<wait.h>
#include<stdlib.h>
#define E_MSG(str, value) do{perror(str); return (value);} while(0)
int main(void){
int signal;
pid_t pid = fork();
if(pid == -1) E_MSG("fork", -1);
if(pid == 0){//运行子进程代码
printf("Run child process %d\n", getpid());
getchar();
exit(-1);
}
else {//运行父进程代码
//父进程回收子进程的资源,阻塞状态
wait(&signal);
if(WIFEXITED(signal)) //子进程正常终止
printf("exit code: %d\n", WEXITSTATUS(signal));
if(WIFSIGNALED(signal))//子进程被其他程序打断
printf("Signum... %d \n", WTERMSIG(signal));
printf("parent process...%d", getpid());
}
return 0;
}
waitpid
用法
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<wait.h>
#include<stdlib.h>
#define E_MSG(str, value) do{perror(str); return (value);} while(0)
int main(void){
int signal;
pid_t pid = fork();
if(pid == -1) E_MSG("fork", -1);
if(pid == 0){//运行子进程代码
printf("Run child process %d\n", getpid());
getchar();
exit(-1);
}
else {//运行父进程代码
int w = waitpid(-1, &signal, WNOHANG); //父进程回收子进程的资源,非阻塞
if(w == 0){//没有子进程的终止
printf("parent exit...");
return 0;
}
if(WIFEXITED(signal)) //子进程正常终止
printf("exit code: %d\n", WEXITSTATUS(signal));
if(WIFSIGNALED(signal))//子进程被其他程序打断
printf("Signum... %d \n", WTERMSIG(signal));
printf("parent process...%d", getpid());
}
return 0;
}
网友评论