您的位置:首页 > 其它

1.写多进程,一个父进程,两个子进程,一个运行ls –l, 另一个暂停5s,父进程先阻塞等待第一个子进程的结束,然后用非阻塞等另一个进程退出,收集到第二个子进程结束的信息,父进程就返回。

2016-08-09 20:49 791 查看
#include<stdio.h>

#include<sys/types.h>

#include<unistd.h>

#include<stdlib.h>

#include<sys/wait.h>

int main()

{
pid_t child1, child2, father;

//child2=fork();
child1=fork();

if(child1 < 0)
{
printf("child1 is error\n");
exit(1);
}
else if(child1 == 0)
{
printf("child1 execute ls-l\n");
execlp("/bin/ls","ls","-l","/home/zzd/class",(char *)NULL);
exit(0);

}

else
{
child2=fork();                                         //第2个fork一定要写在这,也就是父进程里面创建一个子进程。放在前面child1会运行2次,也就是实际上变成了4个进程。
if(child2 < 0)
{
printf("child2 is error\n");
exit(0);
}
else if(child2 == 0)
{
printf("child2 sleep for 5 seconds\n");
sleep(5);

exit(0);
}

//wait(NULL);
father=waitpid(child1,NULL,0);
if(father=child1)
printf("child1 success\n");

else
printf("error");

do
{
father=waitpid(child2,NULL,WNOHANG);
}while(father==0);

if(father=child2)
printf("child2 success\n");

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐