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

#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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值