fork()
is used to create a new process. The child process is almost an exact copy of the parent, inheriting its memory, file descriptors, and more. However, there's more happening beneath the hood than meets the eye.
Let’s get started with one simple question, What would be the output of the Below simple C program? Important question is how many times below line will run?printf("But will this executed twice!? ..... with pid %d\n", getpid());
// Necessary headers....
int main()
{
pid_t pid;
printf("This will only executed one time Executing in parent with pid %d\n", getpid());
pid = fork();
printf("But will this executed twice!? Executing in Parent/Child with pid %d\n", getpid());
if (pid < 0)
{
fprintf(stderr, "fork failed");
return 1;
}
else if (pid == 0)
{
printf("Executing in child with pid %d\n", getpid());
}
else
{
wait(NULL);
printf("Child complete\n");
}
return 0;
}
// Output
This will only executed one time Executing in parent with pid 77433
But this will executed twice time Executing in Parent/Child with pid 77433
But this will executed twice time Executing in Parent/Child with pid 77434
Executing in child with pid 77434
Child complete
Why does this happens? code before the fork() call runs only once but after that runs twice!?
That’s is because When fork clones a parent process, it clones almost exactly as it is so that both execute from same point after fork. This is because of program counter value in PCB for Child and Parent Processes
How does fork returns Child’s process PID to Parent process and 0 to Child process?
To answer this question we need to dig into Real syscall fork not the one in C library (glibc)
Stay Tuned for next part : )