7

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.

Ankur
  • 11,239
  • 22
  • 63
  • 66

5 Answers5

8

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().

Thomas
  • 4,208
  • 2
  • 29
  • 31
  • 1
    There's also the "fork, let one instance continue work and the second check-point the state of computation to stable storage". – Vatine Apr 03 '11 at 08:39
  • I guess this cannot be achieved using just multiple threads.. is it because in order to allocate new resources(TCP Sockets) we need new processes and threads alone cannot do this as they share common resources?? – Nithish Inpursuit Ofhappiness Jun 26 '13 at 16:21
6

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.

Community
  • 1
  • 1
hlovdal
  • 26,565
  • 10
  • 94
  • 165
1

If you have some kind of server listening for incoming connections, you can fork a child process to handle the incoming request (which will not necessarily involve exec or pipes).

hlovdal
  • 26,565
  • 10
  • 94
  • 165
1

A "usage" of fork is to create a Fork Bomb

heijp06
  • 11,558
  • 1
  • 40
  • 60
0

I have written a small shell, and it was full of forks (yes this is exec..), especially for piping elements. wikipedia page on pipe

Aif
  • 11,015
  • 1
  • 30
  • 44