fork()系统调用使用事例

本文通过一个简单的C语言程序示例,演示了父进程与子进程间的变量共享情况。特别关注了fork系统调用后的变量行为,展示了在父子进程中变量是如何被复制的,并解释了为何在子进程中修改的变量不会影响到父进程中的变量值。

  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*/

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值