fork() 创建10个进程

#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
 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值