Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux fork system call

Tags:

linux

fork

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:

  1. fork()

  2. fork()
    fork()

  3. 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.

like image 463
Anand Karandikar Avatar asked Dec 08 '13 06:12

Anand Karandikar


People also ask

Is OS fork a system call?

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.

What happens when fork () is called?

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.

What does fork () do in Linux?

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.

What does the fork () system call return if it is successful?

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.


2 Answers

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.

like image 83
Duck Avatar answered Oct 05 '22 13:10

Duck


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.

like image 21
Aswin Murugesh Avatar answered Oct 05 '22 11:10

Aswin Murugesh