在fork子中,如果我们修改一个全局变量,它将不会在主程序中被修改。如何在进程fork()之间共享内存?
有没有办法改变子分叉全局变量?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int glob_var;
main (int ac, char **av)
{
int pid;
glob_var = 1;
if ((pid = fork()) == 0) {
/* child */
glob_var = 5;
}
else {
/* Error */
perror ("fork");
exit (1);
}
int status;
while (wait(&status) != pid) {
}
printf("%d\n",glob_var); // this will display 1 and not 5.
}
可能重复的[如何在C中使用Linux共享内存](http://stackoverflow.com/questions/5656530/how-to-use-shared-memory-with-linux-in-c) – alk