fork进程之间的数据共享问题

子进程会拷贝父进程的所有资源,变量。

注意:子进程拷贝了父进程数据空间、堆、栈等资源的副本,

父子进程间不共享这些存储空间,共享的空间只有代码段,

子进程修改一个全局变量,父进程的这个全局变量不会改变,因为是一个副本。

所以下面的程序子进程不会输出:

#include <unistd.h>
#include <stdio.h>

int main()
{
  pid_t pid;
  pid = fork();
  int countf = 0;
  int counts = 0;
  int n = 0;
  if(pid == -1){
    perror("fork failed");exit(1);
  }
  else if (pid > 0) {
    sleep(1); // wait for sub-process exit, except to be a orphan
    while(1) {
      printf("parent_pid = %d, parentID = %d\n", getpid(), getppid());
      scanf("%d", &n);
      countf++;
    }
  }
  else if (pid == 0) {
    while(1){
      if(counts != countf)
        printf("child_pid = %d, parentID = %d, count=%d\n", getpid(), getppid(), countf);
        counts = countf;
    }
  }
  printf("This is an end
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值