如何在Process叉()之間共享內(nèi)存?在叉子程序中,如果我們修改一個(gè)全局變量,它將不會(huì)在主程序中被更改。有辦法改變子叉中的全局變量嗎?#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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
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 關(guān)注
- 441 瀏覽
添加回答
舉報(bào)
0/150
提交
取消