linux创建进程函数函数,linux下fork函数创建进程

#include

#include

#include

#include

#include

int main()

{

pid_t child1,child2,child; /*创建两个子进程*/

child1=fork();

//child2=fork(); /*子进程1的出错处理*/

if(child1==-1)

{

printf("Child1 fork error\n");

exit(1); /*异常退出*/

}

/*在子进程1中调用execlp()函数*/

if(child1!=0)

{

child2=fork();

if(child2==-1)

{

printf("Child2 fork error\n");

exit(1); /*异常退出*/

} /*在子进程2中使其暂停5s*/

else if(child2==0)

{

printf("I am child2.I will sleep for 5 seconds!\n");

sleep(5);

printf("I am child2.I have awaked and I will exit!\n");

exit(0); /*正常退出*/

} /*在父进程中等待两个子进程的退出*/

else

{

printf("I am father progress\n");

child=waitpid(child1,NULL,0);/*阻塞式等待*/

if(child==child1)

{

printf("I am father progress.I get child1 exit code:%d\n",child);

}

else

{

printf("Error occured!\n");

}

do

{

child=waitpid(child2,NULL,WNOHANG);/*非阻塞式等待*/

if(child==0)

{

printf("I am father progress.The child2 progress has not exited!\n");

sleep(1);

}

}while(child==0);

if(child==child2)

{

printf("I am father progress.I get child2 exit code:%d\n",child);

}

else

{

printf("Erroe occured!\n");

}

}

}

else if(child1==0)

{

printf("I am child1 and I execute 'ls -l'\n");

if(execlp("ls","ls","-l",NULL)<0)

{

printf("Child1 execlp error\n");

}

} /*子进程2的出错处理*/

exit(0);

}

运行结果:

0818b9ca8b590ca3270a3433284dd417.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值