c++ - 关于fork系统调用和全局变量

标签 c++ unix linux-kernel fork

我有一个 C++ 程序,它 fork 了两个新进程:

#include <pthread.h>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>
using namespace std;

int shared;

void func(){
  extern int shared;
  for (int i=0; i<10;i++)
        shared++;
  cout<<"Process "<<getpid()<<", shared "
        <<shared<<", &shared "
        <<&shared<<endl;
}

int main(){
  extern int shared;
  pid_t p1,p2;
  int status;
  shared=0;
  if ((p1=fork())==0) {func();exit(0);};
  if ((p2=fork())==0) {func();exit(0);};
  for(int i=0;i<10;i++)
        shared++;
  waitpid(p1,&status,0);
  waitpid(p2,&status,0);;
  cout<<"shared variable is: "<<shared<<endl;
  cout<<"Process "<<getpid()<<", shared "
        <<shared<<", &shared "
        <<&shared<<endl;
}

两个 fork 进程对共享变量进行递增,父进程也做同样的事情。由于该变量属于每个进程的数据段,因此最终值为10,因为增量是独立的。

但是共享变量的内存地址是一样的,你可以试着编译看看程序的输出。这怎么解释呢?我无法理解,我以为我知道 fork() 是如何工作的,但这看起来很奇怪..

我需要解释为什么地址相同,尽管它们是不同的变量。

最佳答案

操作系统正在使用 virtual memory和类似的技术,以确保每个进程在相同的地址看到不同的内存单元(虚拟或读取);只有显式共享(例如通过 shm)的内存是共享的,默认情况下所有内存在不同的进程之间是分开的。

关于c++ - 关于fork系统调用和全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1252712/

相关文章:

c++ - 需要精确的线程休眠。最大 1ms 误差

linux - 为什么 cat 0>file 不起作用

linux - shell脚本中的新行

linux-kernel - 对于共享中断线,如何找到要使用的中断处理程序?

c++ - 类似iOS UIKit Dynamics的Qt/C++物理引擎

java - Base-64转Mat转换opencv

c - Linux内核: likely() vs unlikely()

linux - 在 Linux 中检测从 PCIe 端点到主机内存的事务

c++ - 编译后的程序如何与操作系统交互?

python打印只在本地显示