关于fork系统调用和全局变量 [英] About fork system call and global variables

查看:296
本文介绍了关于fork系统调用和全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个程序在C + +,分叉两个新的进程:

I have this program in C++ that forks two new processes:

#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;
}

两个分叉进程对共享变量进行增量,一样。由于变量属于每个进程的数据段,因此最终值为10,因为增量是独立的。

The two forked processes make an increment on the shared variables and the parent process does the same. As the variable belongs to the data segment of each process, the final value is 10 because the increment is independent.

但是,共享变量的内存地址是相同的,你可以尝试编译和观察程序的输出。如何解释?我不明白,我想我知道fork()如何工作,但这似乎很奇怪。

However, the memory address of the shared variables is the same, you can try compiling and watching the output of the program. How can that be explained ? I cannot understand that, I thought I knew how the fork() works, but this seems very odd..

我需要一个解释为什么地址是一样的,

I need an explanation on why the address is the same, although they are separate variables.

推荐答案

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

The OS is using virtual memory and similar techniques to ensure that each process sees different memory cells (virtual or read) at the same addresses; only memory that's explicitly shared (e.g. via shm) is shared, all memory by default is separate among separate processes.

这篇关于关于fork系统调用和全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆