linux下通过调用fork函数实现多进程

41 篇文章 1 订阅
20 篇文章 0 订阅

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
int main(void){
  pid_t pid = fork();
	if(!pid){
	   printf("the id of Children is %d\n",getpid());
		 printf("the id of Parents is %d\n",getppid());
	   exit(0);
	}
	printf("the id of Children is %d\n",pid);
	printf("the id of Parents is %d\n",getpid());
	return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int a;
int b = 10;
int main(void)
{
	pid_t pid = fork();
  int c = 20;
	int *p = (int *)malloc(4);
	*p = 30;
  if(!pid){
	    a = 100;
	    b = 100;
	    c = 100;
            *p = 100;
	    printf("a = %d b = %d c = %d *p = %d\n",a,b,c,*p);
	    exit(0);
	}
	printf("a = %d b = %d c = %d *p = %d\n",a,b,c,*p);

	return 0;
}
调用fork后 后面的代码父子进程都会执行一次,但是因为变量在不同的区域,父子进程只会公用代码区的数据,其他区例如全局区,bss区,堆区,栈区,子进程只会复制父进程。但是存储的空间子进程和父进程是两个独立的部分



#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main(void){
	 int fd = open("a.txt",O_RDWR|O_CREAT|O_TRUNC,0666);
	 pid_t pid = fork();
	 if (!pid){
		  sleep(1);
	    write(fd,"abc",3);
	    close(fd);
			exit(0);
	 }
   write(fd,"123",3);
	 close(fd);
	 return 0;
}

父子进程共享一个文件表,使用同一个文件指针

打出的结果是


#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main(void){
	 pid_t pid = fork();
	 int fd = open("a.txt",O_RDWR|O_CREAT,0666);
	 if (!pid){
		  sleep(1);
	    write(fd,"abc",3);
	    close(fd);
			exit(0);
	 }
   write(fd,"1234",4);
	 close(fd);
	 return 0;
}

open被父子进程调用了两次,打开了两个文件表,导致会发生重写覆盖的效果















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值