#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
int main ()
{
pid_t fpid; //fpid表示fork函数返回的值
int count=0;
int status,i;
fpid=fork();
if (fpid < 0)
printf("error in fork!");
else if (fpid == 0) {
sleep(10);
printf("I am the child process, my process id is %d\n",getpid());
count++;
exit(123);
}
else {
printf("I am the parent process, my process id is %d\n",getpid());
count++;
int res = wait(&status);
i = WEXITSTATUS(status);
printf("The child exits status:%d\n", i);
}
printf("count is: %d\n",count);
return 0;
}
编译执行上面的代码,然后,删除下面两行代码再次编译执行。
int res = wait(&status);
i = WEXITSTATUS(status);
对比两次执行结果,很容易发现wait的作用:让父进程等待子进程执行结束并且接收子进程的退出状态。
什么场景需要用到wait?当子进程和父进程协同完成一项任务并且在父进程中汇总任务结果的时候。
本文的主题,便是探讨如何实现wait和exit。
在父进程中使用wait。流程如下:
在子进程中使用exit。流程如下:
原文:https://www.cnblogs.com/chuganghong/p/15056510.html