Chinaunix

标题: 问一个linux下fork的问题 [打印本页]

作者: h_virus    时间: 2009-02-04 11:58
标题: 问一个linux下fork的问题
我想知道,1、在linux 下, 全局变量是 进程间共享还是独立的,
           2、为什么fork创建进程后,父子进程打出的局部变量地址是一样的呢

我理解的:fork创建进程,实际上是分配一块内存,子进程复制父进程的数据,上下文,等,如果 这样,父子进程的局部变量地址肯定是不一样的啊,为什么下面的程序
实验结果父子进程的局部变量地址是一样的呢
程序:
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdarg.h>


int glob = 6;
char buf[]= " a write to stdout\n";


int main(void)
{
pid_t pid;
int var = 0;
var = 88;

printf("%s", buf);;
printf("%s", " before fork\n");

if ((pid = fork()) < 0)
  printf("fork error");
else if (0 == pid) {
  glob++;
  var++;
} else {
  sleep(2);
}

printf(" pid = %d, glob = %d, var = %d.\n address of gloab glob is %ld, address of local var is %ld \n",
         getpid(), glob, var, &glob, &var);
exit(0);
}


测试结果:

[root@localhost c_testy]# ./tst
a write to stdout
before fork
pid = 13072, glob = 7, var = 89.
address of gloab glob is 134518672, address of local var is -1074189712
pid = 13071, glob = 6, var = 88.
address of gloab glob is 134518672, address of local var is -1074189712
[root@localhost c_testy]# uname -a
Linux localhost.localdomain 2.6.9-42.ELsmp #1 SMP Wed Jul 12 23:27:17 EDT 2006 i686 i686 i386 GNU/Linux
[root@localhost c_testy]#
作者: 雨过白鹭洲    时间: 2009-02-04 12:25
fork就是完全复制一个进程,物理内存怎么分配不去管它,两个进程是独立的虚拟地址空间

1、在linux 下, 全局变量是 进程间共享还是独立的,
    不会共享的
2、为什么fork创建进程后,父子进程打出的局部变量地址是一样的呢
    因为两个进程处于独立的虚拟地址空间,虽然实际的物理地址肯定不一样
作者: zhuhefang2006    时间: 2009-02-04 13:21
同意楼上的回答




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2