fork 创建进程
最后更新于:2022-04-02 04:06:30
[TOC]
## 创建进程
- fork系统调用是用于创建进程的
- fork创建的进程初始化状态与父进程一样
- 系统会为fork的进程分配新的资源
## fork 函数
- fork系统调用无参数
- fork会**返回两次**,分别返回子进程id和0
- 返回子进程id的是父进程,返回0的是子进程
## 示例
#include
#include
#include
using namespace std;
int main()
{
int num = 888;
pid_t pid;
pid = fork();
cout << "fork start" << endl;
// pid=0 子进程
if (pid == 0)
{
cout << "这是一个子进程" << endl;
while (true)
{
num++;
cout << "num in son process:" << num << endl;
sleep(1);
}
}
// pid>0 父进程,返回子进程ip
else if (pid > 0)
{
cout << "这是一个父进程" << endl;
cout << "子进程id: " << pid << endl;
while (true)
{
num--;
cout << "num in father process:" << num << endl;
sleep(1);
}
}
else if (pid < 0)
{
cout << "创建进程失败 " << endl;
}
return 0;
}
```
编译运行 ``` > g++ main.cpp && ./a.out fork start 这是一个父进程 子进程id: 12543 num in father process:887 fork start 这是一个子进程 num in son process:889 num in son process:890 num in father process:886 num in son process:891 num in father process:885 num in son process:892 num in father process:884 ``` > 相等于子进程 fork
';
main.cpp
```#include编译运行 ``` > g++ main.cpp && ./a.out fork start 这是一个父进程 子进程id: 12543 num in father process:887 fork start 这是一个子进程 num in son process:889 num in son process:890 num in father process:886 num in son process:891 num in father process:885 num in son process:892 num in father process:884 ``` > 相等于子进程 fork