Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applications of fork system call

Tags:

fork

unix

fork is used to create a copy of process from which its called. This is typically followed by calls to exec family of functions. Are there any usages of fork other than this? I can think of one. Doing IPC with pipe functions.

like image 675
TL36 Avatar asked Aug 28 '09 06:08

TL36


2 Answers

Yes of course. It's quite common to start a process, do some data initialization and then spawn multiple workers. They all have the same data in their address space and it's Copy On Write.

Another common thing is to have the main process listen to a TCP socket and fork() for every connection that comes in. That way new connections can be handled immediately while existing connections are handled in parallel.

I think you're forgetting that after a fork(), both processes have access to all data that existed in the process before the fork().

like image 70
Thomas Avatar answered Sep 25 '22 19:09

Thomas


Another use of fork is to detach from the parent process (falling back to init, process 1). If some process, say bash with pid 1111, starts myserver which gets pid 2222, it will have 1111 as parent. Assume 2222 forks and the child gets pid 3333. If now process 2222 exits, the 3333 will loose its parent, and instead it will get init as its new parent.

This strategy is sometimes used by deamons when starting up in order to not have a parent relationship with the process that started it. See also this answer.

like image 37
hlovdal Avatar answered Sep 26 '22 19:09

hlovdal