Home > Mobile >  Understanding fork()
Understanding fork()

Time:04-16

i have a question about this Code:

int id = fork();
if (id != 0)
    fork();

printf("FORK: %d\n PID: %d\n PPID:%d\n", id, getpid(), getppid());

}

This is an example Output:

FORK: 5888

PID: 5887

PPID:5239

FORK: 0

PID: 5888

PPID:5887

FORK: 5888

PID: 5889

PPID:5887

I understand the code like this:

The parent process creates with int id = fork(); another process. The parent process thus has the process ID of the child process as the return value in id and the child process has a value of 0. With the condition if (id != 0) { fork (); } A child process WILL be created again in the parent process. Thus, the parent process has two "children". What confuses me about the output: Shouldn't two of the three processes (with the PID 5888 and 5889) have a value of 0 in the fork() since both are child processes? Also, the process with ID 5889 in the fork() has the process id 5888, but wouldn't that mean that 5888 is a child of 5889?

I probably just don't quite understand the principle of fork(), but I would still be grateful for any help.

CodePudding user response:

They should both have id = 0 but you didn't assign the id in the second fork. For the second question the pids do not have a particular order of assignment and are managed entirely by the kernel.

  • Related