linux中的fork函数,用来给当前进程中创建一个新进程,新进程为子进程,原进程为父进程
Fork运行规则 : 以父进程为模板,创建子进程
进程调用fork后,内核做的事
- 分配新的内存块和内核数据结构给子进程
- 将父进程部分数据内容拷贝至子进程
- 添加子进程到系统进程列表中
- fork返回,开始调度器调度
子进程会拷贝父进程的数据作为自己的
- 将父进程的PCB拷贝,并稍加修饰,成为子进程的PCB
- 将父进程的虚拟地址空间拷贝一份,作为子进程的地址空间
#include <stdio.h>
2 #include <unistd.h>
3
4 int main(){
5 pid_t ret = fork();
6 if(ret>0){
7 int count = 5;
8 //father
9 while (count > 0){
10 printf("father %d\n",getpid());
11 --count;
12 sleep(1);
13 }
14 }else if(ret == 0){
15 //child
16 while(1){
17 printf("child %d , %d\n",getpid(),getppid());
18 sleep(1);
19 }
20 }else{
21 perror("fork");
22 }
23 return 0;
24 }
程序输出结果:
可以看到此时test程序下有 pid为1738的父进程,与pid为1739的子进程
fork的返回值
- 父进程中返回子进程的pid
- 子进程返回0
所以 ret==0时执行的是子进程,ret!=0执行的是父进程
父子进程执行顺序没有先后关系,全靠调度器来实现