进程控制 linux中fork同时创建多个子进程注意事项

               

/******************************************************************************************************************

参考:http://blog.sina.com.cn/s/blog_605f5b4f0100x444.html

说明:linux中fork同时创建多个子进程注意事项。

******************************************************************************************************************/ 

            也算实验出来了吧,不过还好有网络,不然好多自己解决不了的问题真就解决不了了。我先写了个这样的创建多个子进程的程序(模仿书上创建一个进程的程序):

#include <stdio.h>#include <sys/types.h>#include <sys/wait.h>#include <stdlib.h>int main(void)pid_t childpid1, childpid2, childpid3; int status; int num; childpid1 = fork(); childpid2 = fork(); childpid3 = fork(); if( (-1 == childpid1)||(-1 == childpid2)||(-1 == childpid3)) {  perror("fork()");  exit(EXIT_FAILURE); } else if(0 == childpid1) {  printf("In child1 process\n");  printf("\tchild pid = %d\n", getpid());  exit(EXIT_SUCCESS); }  else if(0 == childpid2)  {   printf("In child2 processd\n");   printf("\tchild pid = %d\n", getpid());   exit(EXIT_SUCCESS);  }   else if(0 == childpid3)   {    printf("In child3 process\n");    printf("\tchild pid = %d\n", getpid());    exit(EXIT_SUCCESS);   }    else    {     wait(NULL);     puts("in parent");   //  printf("\tparent pid = %d\n", getpid());   //  printf("\tparent ppid = %d\n", getppid());   //  printf("\tchild process exited with status %d \n", status);    } exit(EXIT_SUCCESS); }

结果搞出两个僵尸来,怎么都想不明白,最后在网上找到了答案。并来回揣摩出来了方法和注意事项:

#include <stdio.h>#include <sys/types.h>#include <sys/wait.h>#include <stdlib.h>int main(void)pid_t childpid1, childpid2, childpid3; int status; int num;  /* 这里不可以一下就创建完子进程,要用 *要 创建-》判断-》使用-》return or exit.更不能这样如test2.c *childpid1 = fork(); *childpid2 = fork(); *childpid3 = fork(); */ childpid1 = fork();            //创建 if(0 == childpid1)            //判断 {                     //进入  printf("In child1 process\n");  printf("\tchild pid = %d\n", getpid());  exit(EXIT_SUCCESS);           //退出 } childpid2 = fork(); if(0 == childpid2) {  printf("In child2 processd\n");  printf("\tchild pid = %d\n", getpid());  exit(EXIT_SUCCESS); } childpid3 = fork(); if(0 == childpid3) {  printf("In child3 process\n");  printf("\tchild pid = %d\n", getpid());  exit(EXIT_SUCCESS); } //这里不可以用wait(NULL),多个子进程是不可以用wait来等待的,它只会等待一个 其它都成僵尸了 waitpid(childpid1, NULL, 0); waitpid(childpid2, NULL, 0); waitpid(childpid3, NULL, 0); puts("in parent"); exit(EXIT_SUCCESS); }

严格照着这样做就不会出现 僵尸,也不会影响其它进程。

创建-》判断-》使用-》return or exit.



           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.youkuaiyun.com/jiangjunshow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值