- 论坛徽章:
- 0
|
我想知道,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]# |
|