linux C一个程序里父子进程全局变量

 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 int global = 0;
 
 int main(void)
 {

  pid_t pid; 
  global = 10;
  printf("the parent %d, global 0x%x %d\n", getpid(), &global, global);
  pid = fork();
  if (pid < 0) {
      printf("fail to fork child process\n");
      exit(1);
  } else if (0 == pid) {
      printf("the chile %d, global 0x%x %d\n", getpid(), &global, global);
      global = 100;
      printf("the chile %d, global 0x%x %d\n", getpid(), &global, global);
      exit(0);
  }
  global++;
  printf("the parent %d, global 0x%x %d\n", getpid(), &global, global);
  return 0;
 }

[uxdb@localhost parentChildProcess]$ ./parentChildProcess1
the parent 126988, global 0x60106c 10
the chile 126989, global 0x60106c 10
the chile 126989, global 0x60106c 100
the parent 126988, global 0x60106c 11

通过执行结果可以看出 子进程从父进程拷贝全局变量的值,全局变量在父子进程的进程空间占用各自的内存空间(虽然虚拟地址相同),父子进程中全局变量各自独立。
如果要在多进程程序里使用全局变量,当前看只能使用共享内存。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值