深入浅出fork()

先看一个简单的例子1:

#include <stdio.h>
#include <sys/types.h>
int main()
{
	pid_t pid;
	int i;
	char *str = "hello!";
    for (i = 0; i<2; i++) {
		if ((pid = fork()) < 0) {
			perror("fork");
			return -1;
		} 
		else if (pid == 0) {	// child
			printf("in child process pid,parent pid:%d\n", getpid(), getppid());	
		}
		else {					//parent
			printf("in parent process pid:%d, child pid:%d\n", getpid(), pid);
			return 0;	
		}	
		
		printf("%s,%d\n", str, getpid());
	}

	return 0;
}

结果:

in child process pid:4305,parent pid:4304
hello!,4305
in child process pid:4306,parent pid:4305
hello!,4306
in parent process pid:4305, child pid:4306
in parent process pid:4304, child pid:4305

再看一个例子2,仅去掉了父进程当中的return 0;语句:

#include <stdio.h>
#include <sys/types.h>
int main()
{
	pid_t pid;
	int i;
	char *str = "hello!";
    for (i = 0; i<2; i++) {
		if ((pid = fork()) < 0) {
			perror("fork");
			return -1;
		} 
		else if (pid == 0) {	// child
			printf("in child process pid,parent pid:%d\n", getpid(), getppid());	
		}
		else {					//parent
			printf("in parent process pid:%d, child pid:%d\n", getpid(), pid);
			//return 0;	
		}	
		
		printf("%s,%d\n", str, getpid());
	}

	return 0;
}

结果:

in child process pid:4331,parent pid:4330
hello!,4331
in child process pid:4332,parent pid:4331
hello!,4332
in parent process pid:4331, child pid:4332
hello!,4331
in parent process pid:4330, child pid:4331
hello!,4330
in child process pid:4333,parent pid:4330
hello!,4333
in parent process pid:4330, child pid:4333
hello!,4330

结合两个小例子的结果,自己分析一下,应该对父子进程资源共享有个大概的体验了吧.例1会产生2个子进程,例2会产生2^2-1个子进程.也就是说,如果父子进程中没有一个在for环循中退出去,那么如果有N次环循,会产生2^N-1个子进程(当然这些子进程中,只有N个是根父进程的子进程,其它的是子进程产生的子进程)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值