当用fork函数创建一个新的子进程的时候,子进程就有了新的生命周期,并将在其自己的地址空间内独立运行。如果我们需要在子进程结束时去做一些处理,可以使用waitpid函数等待子进程结束
pid_t waitpid(pid_t __pid, int *__stat_loc, int __options)
第一个参数__pid为需要等待的进程号,第二个参数为子进程的状态信息,第三个参数为另外的选项,如果不想使用,可以设为0
状态信息:等待子进程结束时把子进程的状态传给status
在这里补充介绍四组宏:
1、WIFEXITED(status): 若此值为非0,表明进程正常结束,此时可通过WEXITSTATUS(status)获取进程退出状态(exit时参数)
2、WIFSIGNALED(status):若此值为非0,表明进程异常终止(被信号中断),此时可通过WTERMSIG(status)获取使得进程退出的信号编号
3、 WIFSTOPPED(status):若此值为非0,表明进程处于暂停状态,此时可通过WSTOPSIG(status)获取使得进程暂停的信号编号
4、 WIFCONTINUED(status) 非0表示进程暂停后已经继续运行
示例代码:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
pid_t Child_pid;Child_pid=fork();//创建子进程
if(Child_pid==0)
{
for(int i=0;i<3;i++)
{
printf("This is a child process!num:%d\n",i);
sleep(2);
}
printf("Child process pid:%d\n",getpid());
printf("parent process pid:%d\n",getppid());
exit(3); //以状态3退出
}
else if(Child_pid<0) //fork返回值为0代表子进程创建失败
{
printf("create child process error!\n");
}
else
{
int status=0;
printf("this is parent process!\n");
waitpid(Child_pid,&status,0); //子进程结束时将子进程状态传给status
if(WIFEXITED(status)) //如果子进程正常退出
{
printf("child exit with %d\n", WEXITSTATUS(status));//输出子进程的退出状态
}
printf("Parent process pid:%d\n",getpid());
printf("parent's parent process pid:%d\n",getppid());
}return 0;
}运行结果:
this is parent process!
This is a child process!num:0
This is a child process!num:1
This is a child process!num:2
Child process pid:6218
parent process pid:6217
child exit with 3
Parent process pid:6217
parent's parent process pid:2939