C语言 如何在进程 fork() 之间共享内存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13274786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to share memory between process fork()?
提问by MOHAMED
In fork child, if we modify a global variable, it will not get changed in the main program.
在 fork child 中,如果我们修改一个全局变量,它不会在主程序中发生变化。
Is there a way to change a global variable in child 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.
}
回答by md5
You can use shared memory (shm_open(), shm_unlink(), mmap(), etc.).
您可以使用共享内存(shm_open(),shm_unlink(),mmap()等)。
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
static int *glob_var;
int main(void)
{
glob_var = mmap(NULL, sizeof *glob_var, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
*glob_var = 1;
if (fork() == 0) {
*glob_var = 5;
exit(EXIT_SUCCESS);
} else {
wait(NULL);
printf("%d\n", *glob_var);
munmap(glob_var, sizeof *glob_var);
}
return 0;
}
回答by Omkant
Changing a global variable is not possible because the new created process (child)is having it's own address space.
无法更改全局变量,因为新创建的进程(子进程)拥有自己的地址空间。
So it's better to use shmget(),shmat()from POSIXapi
所以最好使用shmget(), shmat()from POSIXapi
Or You can use pthread, since pthreadsare sharing the globaldata and the changes in global variable is reflected in parent.
或者您可以使用pthread,因为pthreads正在共享global数据并且全局变量的更改反映在父级中。

