wait函数只要有子进程终止,就会产生返回值,waitpid函数实现的功能与wait函数基本相同,其区别在于wait函数用于等待所有子进程结束,而waitpid函数仅用于等待某个特定进程结束,这个特定的进程是指其pid与函数中的pid与函数中的参数pid相关时
有以下几种情况。>
1.当pid<-1:等待进程组ID等于pid绝对值的任一子进程时推出。
2.当pid=-1:等待任意一个子进程退出。
3.当pid=0:等待进程组ID等于调用进程的组ID的任一子进程时退出。
4.当pid>0:等待进程Id等于pid的子进程退出。
以下实例使用作业控制的常量WH+NOHANG实现让子进程睡眠3秒,以便在父进程调用waitpid函数时子进程尚未结束,其代码如下。
代码3-9【waitpid.c】
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include <sys/wait.h>
int
main(void)
{
pid_t pid1,pid2;
pid_t waitpidRes;
if ((pid1 = fork()) < 0)
{
printf("fork error: % s\n",strerror(error));
exit(-1);
}
else if (pid1==0)
{
sleep(3);
printf("child process % d exit\n",getpid());
exit(0);
}
if ((pid2 = fork()) < 0)
{
printf("fork error:% s\n",strerror(errno));
exit(-1);
}
else if (pid2==0)
{
printf("child process % d exit\n",getpid());
exit(0);
}
if ((waitpidRes = waitpid(pid1,NULL,0)) == pid1)
{
printf("get termintated child process % d.\n",waitpidRes);
}
else if (waitpidRes < 0)
{
printf("waitpid error:% s\n",strerror(error));
exit(-1);
}
else
{
printf("waitpid return 0 \n");
}
printf("parent process exit \n");
exit(0);
}
运行结果如下: