Tuesday, March 27, 2012

Linux fork() function

Source: http://www.unix.com/unix-dummies-questions-answers/12815-fork-function.html

Let's take:

int main()
{int pid = fork();

as an example. Let's say that it is compiled and is sitting on disk as a file called forktest.

And let's say that forktest starts to run. This means that it must have a pid, let's say that it is pid 25021.

Well, pid 25021 will quickly invoke fork(). This means that the kernel must create a second process. The second process will be the child of process 25021. Let's say that the second process gets a pid of 25079. So now we have two processes: 25021 which is the original and 25079 which is the child.

Now both processes can run. If the system has two cpu's, they can literally run at the same time. But neither process restarts from the beginning. They both continue from where process 25021 was.

Both processes seem to be returning from fork. And both must store a value in pid. Now they do not share a common variable called pid. Each process has a private copy. The variable called pid in process 25021 gets a value of 25079. The variable called pid in process 25079 gets a zero.

Next both processes continue with the next statement. So both processes now exit.

The end.

No comments: