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