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:
- Initially, the program starts executing from the
main()
function. - The line
printf("Before Forking\n");
prints “Before Forking” to the standard output. - The
fork()
system call is used. Whenfork()
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 thefork()
call. - So, after the
fork()
call, there are two identical copies of the program running concurrently. - 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!