/******************************************************************************************************************
参考: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");
-
-
-
- }
- 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;
-
-
-
-
-
-
-
- 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);
- }
-
- waitpid(childpid1, NULL, 0);
- waitpid(childpid2, NULL, 0);
- waitpid(childpid3, NULL, 0);
- puts("in parent");
-
- exit(EXIT_SUCCESS);
-
- }
严格照着这样做就不会出现 僵尸,也不会影响其它进程。
创建-》判断-》使用-》return or exit.