fork 新进程
-
用于创建新的进程
-
引用
#include <unistd.h> -
创建进程
pid_t fork(void);- 调用失败时返回-1
- 调用成功后,将会产生两个执行流,即两个进程
- 对于父进程,成功时将返回进程ID
- 对于子进程,成功时将返回0
- 可用 是否等于0 来区分想要分别执行的代码
- 使用例子
#include <stdio.h> #include <unistd.h> int main() { int pid = fork(); if (pid == -1) { puts("fork() error"); return -1; } if (pid == 0) { printf("I am child, my pid is %d\n", getpid()); } else { printf("I am father, my child’s pid is %d\n", pid); printf("I am father, my pid is %d\n", getpid()); sleep(1); } return 0; }- 输出
I am father, my child’s pid is 2248 I am father, my pid is 2245 I am child, my pid is 2248 - 两个分支都会执行,因为fork本质是依照父进程完美克隆了一个子进程出来
- 所以两个进程都在跑这个代码,只不过他们的执行流中pid值是不一样的
- 子进程中的为0,父进程中的为子进程的真实进程ID
- 注意
- 这里child内打印的pid不是我们fork返回的pid 0
- 而是子进程在操作系统中真实的进程ID
- 输出