天天看點

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