如何在Process叉()之间共享内存?在叉子程序中,如果我们修改一个全局变量,它将不会在主程序中被更改。有办法改变子叉中的全局变量吗?#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.}
3 回答
弑天下
TA贡献1818条经验 获得超8个赞
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;}
- 3 回答
- 0 关注
- 425 浏览
添加回答
举报
0/150
提交
取消