Linux系統程式設計 - 07. 迴圈建立N個子程式分析

世界非世界,是名世界!發表於2020-11-15
book@100ask:~/linux/sys$ cat loop_fork.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(void)
{
	int i;
	pid_t pid;
	printf("Father Process\n");
	
	for(i = 0; i < 5; i++)
	{
		pid = fork();
        if(pid == -1)
        {
           	perror("fork failed!\n");
           	exit(-1);
        }	

        else if(pid == 0)
        {
		    break;     //if fork succed,exit current loop and go to next loop.
		}
	}

	if(i < 5)
	{
		sleep(i);
		printf("I`m %dth child, pid = %u, ppid = %u\n",(i+1),getpid(),getppid());
	}
	else
	{
		sleep(i);
		printf("I`m Father, pid = %u, ppid = %u\n",getpid(),getppid());
	}

	return 0;
}

 

相關文章