Why do processes shared by fork () not go through this function the same way?

I am confused by the fork () function in C / C ++. Given the following code:

void fork2() { printf("LO\n"); fork() printf("L1\n"); fork(); printf("Bye!\n"); } 

Lecture slides give the following diagram

  ______Bye ___L1|______Bye | ______Bye L0|___L1|______Bye 

For me, this diagram makes no sense. I expect that every call to fork will result in a call to printf("LO\n") . Or am I wrong?

+4
source share
5 answers

fork () creates an exact duplicate of the process that caused the fork () function to be called. This means that you have two processes that are exactly the same and located at the same point in the program. If we go through the fork2 () function, the following will happen.

Process A (source process):
L0 (forks of process A creating process B)
L1 (process A expands again, creating process C)
Goodbye! (process output A)

Process b:
L1 (forks of process B creating process D)
Goodbye! (process B exits)

Process C:
Goodbye! (process C exits)

Process D:
Goodbye! (process D exits)

It depends on the operating system in relation to which process it is running on each fork, and whether it switches to another process at any time during execution, so the output can be alternated at any point after the technological forks. For example, if the OS decided to always follow the new process until the end of the function, you will get the following output:

 L0 (A) L1 (B) Bye! (D) Bye! (B) L1 (A) Bye! (C) Bye! (A) 
+7
source

You are wrong. During forking, both the parent and child processes continue from the same place - after calling fork() , and not at the beginning of the function. This is easy to verify - change the name of your function to main() , and then compile and run it:

 #include <unistd.h> #include <stdio.h> int main(int argc, char **argv) { printf("LO\n"); fork(); printf("L1\n"); fork(); printf("Bye!\n"); return 0; } 

Output:

 LO L1 Bye! L1 Bye! Bye! Bye! 

There is nothing like trying to figure out something how it works ...

+15
source

You are mistaken. :) After the plug, both processes will execute the next command, following the plug.

+7
source

The behavior of fork() requires some getting used to, since it actually gives the execution path to the parent and child processes (it returns 0 in the child process and the PID of the child process in the parent process).

This means that after the first call to fork() you will have two processes with the same code, and after the second call you will have four processes (since both processes call the fork() call), still running the same code. Thus, the graph:

  L0 / \ / \ L1 L1 / \ / \ Bye Bye Bye Bye 
+5
source

BTW, fork () is not a C / C ++ library function. This is a library function for calling a Unix system call. There are many C / C ++ implementations that do not have fork ().

0
source

Source: https://habr.com/ru/post/1332251/


All Articles