/******************************************************************************************************************
參考:http://blog.sina.com.cn/s/blog_605f5b4f0100x444.html
說明:linux中fork同時創(chuàng)建多個子進(jìn)程注意事項(xiàng)。
******************************************************************************************************************/
也算實(shí)驗(yàn)出來了吧,,不過還好有網(wǎng)絡(luò),,不然好多自己解決不了的問題真就解決不了了,。我先寫了個這樣的創(chuàng)建多個子進(jìn)程的程序(模仿書上創(chuàng)建一個進(jìn)程的程序):
- #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);
-
- }
結(jié)果搞出兩個僵尸來,怎么都想不明白,,最后在網(wǎng)上找到了答案,。并來回揣摩出來了方法和注意事項(xiàng):
- #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);
-
- }
嚴(yán)格照著這樣做就不會出現(xiàn) 僵尸,也不會影響其它進(jìn)程,。
創(chuàng)建-》判斷-》使用-》return or exit.