1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <unistd.h>
4
5 int main()
6 {
7 int value=0;
8 int childpid;
9
10 fprintf(stderr,"the process before creating pid=%d/n",getpid());
11 if((childpid=fork())==0)
12 {
13 fprintf(stderr,"the child process pid=%d",getpid());
14 fprintf(stderr,"the initial value=%d/n",value);
15 value=1;
16
17 fprintf(stderr,"the value is %d after being changed by the child process/n",value);
18 }
19 else if(childpid>0)
20 {
21 fprintf(stderr,"the parent process pid=%d/n",getpid());
22 fprintf(stderr,"value in parent process is %d/n",value);
23 }else
24 fprintf(stderr,"the fork system call fail");
25 return 0;
26 }
//典型的运行结果
/*the process before creating pid=7151
the parent process pid=7151
value in parent process is 0
the child process pid=7152the initial value=0
the value is 1 after being changed by the child process*/
本文通过一个简单的C语言程序示例,演示了父进程与子进程间的变量共享情况。特别关注了fork系统调用后的变量行为,展示了在父子进程中变量是如何被复制的,并解释了为何在子进程中修改的变量不会影响到父进程中的变量值。
2489

被折叠的 条评论
为什么被折叠?



