fork() 创建10个进程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32095699/article/details/88595751
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{	
	pid_t pid = fork();
	int parent_id;
	if(pid>0){
		parent_id = getpid();
		child_cnt=1;
	}
	else if(pid==0){
		printf("this is child %d ,id = %d\n",0,getpid());
	}
	for (int i = 1; i <= 9; ++i)
	{
		
		if(getpid()==parent_id){

			pid = fork();
			if(pid<0){
				printf("process create failed!\n");
				exit(1);
			}
			else if(pid==0){
				printf("this is child %d ,id = %d\n",i,getpid());
				break;
			}
		}
		
	}
	return 0;
}

输出:

$ ./fork_10 
this is child 0 ,id = 25219
this is child 1 ,id = 25220
this is child 3 ,id = 25222
this is child 2 ,id = 25221
this is child 4 ,id = 25223
this is child 6 ,id = 25225
this is child 5 ,id = 25224
this is child 8 ,id = 25227
this is child 7 ,id = 25226
this is child 9 ,id = 25228
 

创建4个进程:

                                       

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
	

	for (int i = 0; i <2; ++i)
	{
		pid_t pid =fork();
		if(pid<0){
			exit(1);
		}
		else if(pid ==0){
			printf("this is a child,id = %d,pid = %d\n",getpid(),getppid());
		}
		else
			printf("this is parent ,id = %d\n",getpid() );
	}

	return 0;
}

输出:

this is parent ,id = 25083
this is parent ,id = 25083
this is a child,id = 25085,pid = 25083
this is a child,id = 25084,pid = 25083
this is parent ,id = 25084
this is a child,id = 25086,pid = 25084
 

猜你喜欢

转载自blog.csdn.net/qq_32095699/article/details/88595751