日期:2014-05-16  浏览次数:20954 次

进程waitpid options参数的疑惑
下面我写了一个程序,程序的要求如下:子进程用sleep等待10秒,父进程用waitpid函数等待子进程正常结束,父进程在等待的时候不阻塞,每1秒在屏幕上输出一行文字,若发现子进程退出,打印出等待进程的进程号(PID)和退出状态。
我的代码如下 :
int main()
{
pid_t result;
int status;
result = fork();
if (result == -1)
{
perror("copy process wrong");
exit(1);
}
else if (result == 0)
{
printf("this is child process ,the PID is %d\n", getpid());
sleep(10);
exit(0);
}
else
{
waitpid(result, &status, WNOHANG);//这里不太清楚
printf("now waiting for the child process ending......\n");
if (0 == WIFEXITED(status))
sleep(1);
else
{
printf("child process ending ritght states%d\n",WIFEXITED(status));
exit(0);
}
}
return 0;
}
我不知道waitpid的第三个参数这样用对不对,现在我的程序只能打印1次,不能做到打印10次.不知道问题出在哪里,请高手指教,谢谢

------解决方案--------------------
WNOHANG 参数用法没有问题,表示即使当前子进程尚未结束,waitpid()也不会阻塞

你的程序之所以打印一次,是因为父进程没有循环

while(1)
{
waitpid(result, &status, WNOHANG);//这里不太清楚
printf("now waiting for the child process ending......\n");
if (0 == WIFEXITED(status))
sleep(1);
else
{
printf("child process ending ritght states%d\n",WIFEXITED(status));
exit(0);
}
}