I am having some trouble understanding how to use Unix\'s fork()
. I am used to, when in need of parallelization, spawining threads in my application. It\'s always s
It would be more valid to ask why CreateNewThread
doesn't just return a thread id like fork() does... after all fork()
set a precedent. Your opinion's just coloured by you having seen one before the other. Take a step back and consider that fork()
duplicates the process and continues execution... what better place than at the next instruction? Why complicate things by adding a function call into the bargain (and then one what only takes void*
)?
Your comment to Mike says "I can't understand is in which contexts you'd want to use it.". Basically, you use it when you want to:
BTW / using UNIX/Linux doesn't mean you have to give up threads for fork()
ing processes... you can use pthread_create() and related functions if you're more comfortable with the threading paradigm.
History aside, there are some fundamental differences with respect to ownership of resource and life time between processes and threads.
When you fork, the new process occupies a completely separate memory space. That's a very important distinction from creating a new thread. In multi-threaded applications you have to consider how you access and manipulate shared resources. Processed that have been forked have to explicitly share resources using inter-process means such as shared memory, pipes, remote procedure calls, semaphores, etc.
Another difference is that fork()'ed children can outlive their parent, where as all threads die when the process terminates.
In a client-server architecture where very, very long uptime is expected, using fork() rather than creating threads could be a valid strategy to combat memory leaks. Rather than worrying about cleaning up memory leaks in your threads, you just fork off a new child process to process each client request, then kill the child when it's done. The only source of memory leaks would then be the parent process that dispatches events.
An analogy: You can think of spawning threads as opening tabs inside a single browser window, while forking is like opening separate browser windows.
fork()
says "copy the current process state into a new process and start it running from right here." Because the code is then running in two processes, it in fact returns twice: once in the parent process (where it returns the child process's process identifier) and once in the child (where it returns zero).
There are a lot of restrictions on what it is safe to call in the child process after fork()
(see below). The expectation is that the fork()
call was part one of spawning a new process running a new executable with its own state. Part two of this process is a call to execve()
or one of its variants, which specifies the path to an executable to be loaded into the currently running process, the arguments to be provided to that process, and the environment variables to surround that process. (There is nothing to stop you from re-executing the currently running executable and providing a flag that will make it pick up where the parent left off, if that's what you really want.)
The UNIX fork()-exec()
dance is roughly the equivalent of the Windows CreateProcess()
. A newer function is even more like it: posix_spawn()
.
As a practical example of using fork()
, consider a shell, such as bash
. fork()
is used all the time by a command shell. When you tell the shell to run a program (such as echo "hello world"
), it forks itself and then execs that program. A pipeline is a collection of forked processes with stdout
and stdin
rigged up appropriately by the parent in between fork()
and exec()
.
If you want to create a new thread, you should use the Posix threads library. You create a new Posix thread (pthread) using pthread_create()
. Your CreateNewThread()
example would look like this:
#include <pthread.h>
/* Pthread functions are expected to accept and return void *. */
void *MyFunctionToRun(void *dummy __unused);
pthread_t thread;
int error = pthread_create(&thread,
NULL/*use default thread attributes*/,
MyFunctionToRun,
(void *)NULL/*argument*/);
Before threads were available, fork()
was the closest thing UNIX provided to multithreading. Now that threads are available, usage of fork()
is almost entirely limited to spawning a new process to execute a different executable.
below: The restrictions are because fork()
predates multithreading, so only the thread that calls fork()
continues to execute in the child process. Per POSIX:
A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources. Consequently, to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called. [THR] [Option Start] Fork handlers may be established by means of the pthread_atfork() function in order to maintain application invariants across fork() calls. [Option End]
When the application calls fork() from a signal handler and any of the fork handlers registered by pthread_atfork() calls a function that is not asynch-signal-safe, the behavior is undefined.
Because any library function you call could have spawned a thread on your behalf, the paranoid assumption is that you are always limited to executing async-signal-safe operations in the child process between calling fork()
and exec()
.
Letting the difference between spawning a process and a thread set aside for a second: Basically, fork() is a more fundamental primitive. While SpawnNewThread has to do some background work to get the program counter in the right spot, fork does no such work, it just copies (or virtually copies) your program memory and continues the counter.
Fork()'s most popular use is as a way to clone a server for each new client that connect()s (because the new process inherits all file descriptors in whatever state they exist). But I've also used it to initiate a new (locally running) service on-demand from a client. That scheme is best done with two calls to fork() - one stays in the parent session until the server is up and running and able to connect, the other (I fork it off from the child) becomes the server and departs the parent's session so it can no longer be reached by (say) SIGQUIT.
Fork has been with us for a very, very, long time. Fork was thought of before the idea of 'start a thread running a particular function' was a glimmer in anyone's eye.
People don't use fork
because it's 'better,' we use it because it is the one and only unprivileged user-mode process creation function that works across all variations of Linux. If you want to create a process, you have to call fork
. And, for some purposes, a process is what you need, not a thread.
You might consider researching the early papers on the subject.