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