Recently I faced an technical interview in a reputed IT firm. the interviewer asked me about how many processes will be created if the following 3 different fork system call invocations are given:
fork()
fork()
fork()
fork()
fork()
fork()
The answer to first was obvious 2 processes.
2nd one will start 3 processes.
bt the 3rd I told was 5 processes, the interviewer disagreed and said its 7.
I cannot figure out how did it create 7 processes.
Please help.
In an operating system, a fork is a Unix or Linux system call to create a new process from an existing running process. The new process is a child process of the calling parent process.
When a process calls fork, it is deemed the parent process and the newly created process is its child. After the fork, both processes not only run the same program, but they resume execution as though both had called the system call.
In the computing field, fork() is the primary method of process creation on Unix-like operating systems. This function creates a new copy called the child out of the original process, that is called the parent. When the parent process closes or crashes for some reason, it also kills the child process.
Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.
You need to nail the interviewer down on whether it is total processes or created processes. This is a simple technique (in most of these fork
puzzles) on a posix system.
int main(int argc, char *argv[])
{
fork();
printf("%d\n", getpid());
fork();
printf("%d\n", getpid());
fork();
printf("%d\n", getpid());
return(0);
}
And then just run it as: pgm | sort | uniq
9314
9317
9318
9319
9320
9321
9322
9323
8 total processes, seven created ones.
The third one:
fork()
fork()
fork()
After the first fork, you have 2 processes. So the second fork is called by 2 processes. So, you have 4 processes after the second fork(). The third fork is called by all 4 processes, creating 4 more processes. So, you have 8 processes in total, where 7 processes are created.
Thus, for n forks, there will be a total of 2^n
processes, where 2^n-1
processes are created due to the forks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With