进程控制 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.



           

猜你喜欢

转载自blog.csdn.net/qq_44925290/article/details/89786067
今日推荐