简体   繁体   中英

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.

When using fork with an if statement, how many times will the child process be created in the following code?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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