educative.io

Fork() execution

execution splits into two processes after fork(). In output here we have duplication of a message which was before the fork()

Hi @Sitora_Tuychieva,
Let me explain why we have duplication of a message in the output.

Referring to the following code:

  1. Initially, the program starts executing from the main() function.
  2. The line printf("Before Forking\n"); prints “Before Forking” to the standard output.
  3. The fork() system call is used. When fork() is called, it creates a new process that is a copy of the current process. Both the parent process and the child process continue execution from the line immediately after the fork() call.
  4. So, after the fork() call, there are two identical copies of the program running concurrently.
  5. Both copies will execute the printf("After Forking\n"); line, resulting in “After Forking” being printed twice.

Hence, you see “Before Forking” and “After Forking” printed twice, once by the parent process and once by the child process. This behavior is typical when using fork(), where the child process inherits a copy of the parent process’s code and continues executing from the same point as the parent.

I hope this helps!
Thanks!