进程篇—你所不知道的fork

本文详细介绍了fork函数的作用及用法,并通过实例演示了如何使用fork创建新的进程,展示了子进程与父进程之间的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

进程篇—你所不知道的fork

标签:fork

一、fork用法
作用是创建进程,
函数原型:

include

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<unistd.h>
  4 int main()
  5 {
  6     pid_t pid=fork();
  7     if(pid < 0)
  8     {
  9         printf("error\n");
 10     }
 11     else if(pid==0)                                                         
 12     {
 13         printf("I am children,process is %d\n",getpid());
 14     }
 15     else
 16     {
 17         printf("I am father,process is %d\n\n",getppid());
 18     }
 19     return 0;
 20 }  

结果:
I am father,process is 2749
I am children,process is 3516

子进程是父进程的副本,它将获得父进程数据空间、堆、栈等资源的副本。注意,子进程持有的是上述存储空间的“副本”,这意味着父子进程间不共享这些存储空间,他们共享代码段。
UNIX将复制父进程的地址空间内容给子进程,因此,子进程有了独立的地址空间。在不同的UNIX(Like)系统下,我们无法确定fork之后是子进程先运行还是父进程先运行,这依赖于系统的实现。
代码可以很好的表现出来:

1 #include<stdio.h>                                                           
  2 #include<stdlib.h>
  3 #include<unistd.h>
  4 int a=5;
  5 int main()
  6 {
  7     pid_t pid=fork();
  8     if(pid < 0)
  9     {
 10         printf("error\n");
 11     }
 12     else if(pid==0)
 13     {
 14         a++;
 15         printf("I am children,process is %d,a=%d\n",getpid(),a);
 16     }
 17     else
 18     {
 19         printf("I am father,process is %d,a=%d\n",getppid(),a);
 20     }
 21     return 0;
 22 }           

结果:
I am father,process is 2749,a=5`

I am children,process is 4565,a=6

由上面代码可以看出,子进程虽然复制了父进程的堆栈等,但是他们之间是不共享的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值