c - 程序的进程图清楚地显示了从创建到终止的父进程和子进程执行
问题描述
pid_t pid;
printf("Begin");
if (fork() == 0) {
printf("First if fork==0");
if (fork() != 0)
printf("First if fork!=0");
}
if (fork() != 0) {
printf("second if fork!=0");
if (fork() == 0)
printf("second if fork==0");
}
printf("End if\n");
我试图了解它是如何fork
工作的。你能画出一个让我和其他人都能理解的过程图吗?
解决方案
您的示例有四个 fork
s。通常这是以不同的方式完成的
pid_t child_pid = fork();
// both parent and child process return from `fork()` and continue here
if (child_pid == -1) {
// still parent process, error handling
// no child process was created
} else if (child_pid == 0) {
// this is the child process
} else {
// this is the parent process, child_pid > 1
}
现在可以清楚的看到,哪些代码在父进程中运行,哪些在子进程中运行。
回到您的示例,您有一个执行fork
s 的主进程(忽略错误处理)
if (fork() == 0) {
printf("First child process\n");
if (fork() != 0)
printf("First child process (parent part)\n");
/*
else
printf("Grandchild\n");
// fall through for both first child and grandchild
*/
}
// Main process, and first child, and grandchild
if (fork() != 0) {
// also first child and grandchild ("parent" part)
printf("Main process (parent part)\n");
if (fork() == 0)
// also third grandchild, and second great-grandchild
printf("Third child process\n");
}
/*
else
// also second grandchild, and first great-grandchild
printf("Main process, second child\n");
*/
这意味着,你有一个主进程,有三个孩子。第一个子进程也进行了分叉,创建了一个孙子进程。
但是,第一个孩子和第一个孙子继续使用相同的代码到第二个外部 if,因此创建了更多的孩子、孙子和曾孙。
所以,最后主进程有三个孩子。从第一个孩子开始,三个孙子后代,其中第一个孙子有两个自己的曾孙。
除非我忘了一两个左右,当然:-)
推荐阅读
- javascript - 如何获得数组中数字总和的组合
- excel - 为 Excel VBA 创建 VHF 技术指标
- python - 如何将类成员方法的参数列表自动填充到可变参数中?
- python - 从字符串中获取原始文本(来源:excel,数据库)
- reactjs - axios 中的 GraphQL 发布请求
- ios - 如何删除指向 main.storyboard 的 IBAction 链接
- lua - 如何使用对 lua 脚本的内置 mediawiki 支持来解析 wikitext?
- c++ - 指向 C++ 中的向量数组并将其发送到函数
- gradle - 由于 pom 依赖,无法创建我的 JDA 项目的 JAR
- php - 忽略 PHP 警告 SessionHandler::read(): 会话数据文件不是由您的 uid 创建的