Alex Rivera | Logout

What is the purpose of fork()?

Asked 2009-06-12T04:49:06.360
127

In many programs and man pages of Linux, I have seen code using fork(). Why do we need to use fork() and what is its purpose?

Edit
Report

2 Answers

23

fork() is how Unix create new processes. At the point you called fork(), your process is cloned, and two different processes continue the execution from there. One of them, the child, will have fork() return 0. The other, the parent, will have fork() return the PID (process ID) of the child.

For example, if you type the following in a shell, the shell program will call fork(), and then execute the command you passed (telnetd, in this case) in the child, while the parent will display the prompt again, as well as a message indicating the PID of the background process.

$ telnetd &

As for the reason you create new processes, that's how your operating system can do many things at the same time. It's why you can run a program and, while it is running, switch to another window and do something else.

answered 2009-06-12T04:53:48.330
13

fork() is basically used to create a child process for the process in which you are calling this function. Whenever you call a fork(), it returns a zero for the child id.

pid=fork()
if pid==0
//this is the child process
else if pid!=0
//this is the parent process

by this you can provide different actions for the parent and the child and make use of multithreading feature.

answered 2009-06-12T05:02:31.723

Your Answer