在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.
}
Run Code Online (Sandbox Code Playgroud) 你有什么想法用"fork()函数"和"共享内存"块来模拟线程 ......
可能吗 ?
为程序执行此操作有多合理?(我的意思是,它会运作良好吗?)