简体   繁体   English

在fork()中检测子进程创建

[英]Detecting child process creation in fork()

The fork() system call makes two identical copies of the address space, one for parent, the other for the child. fork()系统调用生成两个相同的地址空间副本,一个用于父级,另一个用于子级。

When using fork with an if statement, how many times will the child process be created in the following code? 使用带if语句的fork时,在以下代码中创建子进程的次数是多少?

fork();
pid=fork();
if(pid==0)
{
fork();
}

Add a little extra code to get something like: 添加一些额外的代码来获得类似的东西:

#include <stdio.h>
#include <unistd.h>

int main()
{
    pid_t pid;
    pid = fork();
    if (pid != 0) printf("%d\n", pid);
    pid = fork();
    if (pid != 0) printf("%d\n", pid);
    if(pid==0)
    {
        pid = fork();
        if (pid != 0) printf("%d\n", pid);
    }
    return 0;
}

Then compile, execute, and check its output: 5 child process IDs . 然后编译,执行并检查其输出: 5个子进程ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM