fork函数分析举例

as we all know the exec() family function can only take the executable file to create a new process which replace the original one even the PID is the same to the original one, in contrast the fork funciton create a whole new process .the fork() function duplicates the current process , creating a new entry in the process table with many of the same attributes as the current process, the new process is almost identical to the original , executing the same code but with its own data space , environment , and file descriptors ,

#include <sys/types.h>
#include <unistd.h>

pid_t fok(void);

call to fork in the parent returns the PID of the new child process , the new process continues to execute just link the original , with the exception that in the child process the call to fork returns 0 ,and this allows both the parent and child to determine which is which .


and a typical code fragment using fork is

pid_t new_pid;
new_pid=fork();
switch(new_pid){
     case -1:.........break;
     case 0:..........break;/*child process*/
     default:.....break;/*parent process*/
           
}

now show you an example about it:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main(){
	pid_t num;
	char * mes;
	int n=0;
	int n1=1;
	int n2=1;
	printf("hello , are you ready\n");
	num=fork();
	switch(num){
		case -1:{
			printf("error\n");
			break;
		}
		case 0:{
			mes="child";
		    n1=5;
			n=5;
			break;
		}
		default:{
			mes="parent";
		    n2=3;
			n=2;
			break;
		}
	}

	for(int i=0;i<n1;i++){
		printf("%s--------%d\n",mes,getpid());
		sleep(1);
	}
	for(int i=0;i<n2;i++){
		printf("%s>>%d\n",mes,getpid());
		sleep(1);
	}
	printf("\n");

	for(int i=0;i<n;i++){
		printf("%s---%d",mes,i);
		sleep(1);
	}
return 0;
}

and the result is as follows:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值