42

So, I have used fork() and I know what it does. As a beginner I was quite afraid of it (and I still don't understand it fully). The general description of fork() that you can find online is, that it copies the current process and assigns different PID, parent PID and the process will have different address space. All is good, however, given this functionality description a beginner would wonder "Why is this function so important... why would I want to copy my process?". So I did wonder and eventually I found out that's how you can call other processes from within your current process by means of the execve() family.

What I still don't understand is why do you have to do that this way? The most logical thing would be to have a function that you can call like

create_process("executable_path+name",params..., more params); 

which would spawn a new process and start running it at the beginning of main() and return the new PID.

What bothers me is the feeling that the fork/execve solution is doing potentially unneeded work. What if my process is using tons of memory? Does the kernel copy my page tables and such. I am sure it doesn't really allocate real memory unless I have touched it. Also, what happens if I have threads? It just seems to me that it's too messy.

Almost all description of what fork does, say it just copies the process and the new process starts running after the fork() call. This is indeed what happens but why does it happen this way and why is fork/execve the only way to spawn new processes and what is the most general unix way of creating a new process from your current one? Is there any other more effective way to spawn process?** Which wouldn't require to copy more memory.

This thread talks about the same issue, but I found it not quite satisfactory:

Thank you.

5

14 Answers 14

30
+50

This is due to historical reasons. As explained at https://www.bell-labs.com/usr/dmr/www/hist.html, very early Unix did have neither fork() nor exec*(), and the way the shell executed commands was:

  • Do the necessary initialization (opening stdin/stdout).
  • Read a command line.
  • Open the command, load some bootstrap code and jump to it.
  • The bootstrap code read the opened command, (overwriting the shell's memory), and jumped to it.
  • Once the command ended, it would call exit(), which then worked by reloading the shell (overwriting the command's memory), and jumping to it, going back to step 1.

From there, fork() was an easy addition (27 assembly lines), reusing the rest of the code.

In that stage of Unix development, executing a command became:

  • Read a command line.
  • fork() a child process, and wait for it (by sending a message to it).
  • The child process loaded the command (overwriting the child's memory), and jumped to it.
  • Once the command ended, it would call exit(), which was now simpler. It just cleaned its process entry, and gave up control.

Originally, fork() didn't do copy on write. Since this made fork() expensive, and fork() was often used to spawn new processes (so often was immediately followed by exec*()), an optimized version of fork() appeared: vfork() which shared the memory between parent and child. In those implementations of vfork() the parent would be suspended until the child exec*()'ed or _exit()'ed, thus relinquishing the parent's memory. Later, fork() was optimized to do copy on write, making copies of memory pages only when they started differing between parent and child. vfork() later saw renewed interest in ports to !MMU systems (e.g: if you have an ADSL router, it probably runs Linux on a !MMU MIPS CPU), which couldn't do the COW optimization, and moreover could not support fork()'ed processes efficiently.

Other source of inefficiencies in fork() is that it initially duplicates the address space (and page tables) of the parent, which may make running short programs from huge programs relatively slow, or may make the OS deny a fork() thinking there may not be enough memory for it (to workaround this one, you could increase your swap space, or change your OS's memory overcommit settings). As an anecdote, Java 7 uses vfork()/posix_spawn() to avoid these problems.

On the other hand, fork() makes creating several instances of a same process very efficient: e.g: a web server may have several identical processes serving different clients. Other platforms favour threads, because the cost of spawning a different process is much bigger than the cost of duplicating the current process, which can be just a little bigger than that of spawning a new thread. Which is unfortunate, since shared-everything threads are a magnet for errors.

2
  • Of all the answers, this looks like the only one that should be here :^) Mar 8, 2014 at 21:26
  • The link is dead. To anyone looking for the paper: Title : "The Evolution of the Unix Time-sharing System" Author:"Dennis M. Ritchie"
    – Sidervs
    Jul 10, 2016 at 19:31
12

Remember that fork was invented very early in Unix (& perhaps before) on machines which today seems ridiculously small (eg 64K bytes of memory).

And it is more in phase with the overall (original) philosophy of providing basic mechanisms, not policies, through the most elementary possible actions.

fork just creates a new process, and the simplest way of thinking that is to clone the current process. So the fork semantics is very natural, and it is the simplest machanism possible.

Other system calls (execve) are in charge of loading a new executable, etc..

Separating them (and providing also pipe and dup2 syscalls) gives a lot of flexibility.

And on current systems, fork is implemented very efficiently (through lazy copy on write pagination techniques). It is known that the fork mechanism makes Unix process creation quite fast (e.g. faster than on Windows or on VAX/VMS, which have system calls creating processes more similar to what you propose).

There is also the vfork syscall, which I don't bother using.

And the posix_spawn API is much more complex than fork or execve alone, so illustrates that fork is simpler...

5
  • So, I've heard about spawn, but I wonder, for example, which create-a-new-process method do large well-respected linux applications use (such as Gimp, openoffice, gnome, etc.). I assume at least some of them will have a need to do that.
    – Swetko
    Nov 28, 2011 at 6:46
  • GTK provides (in the Glib library) calls above the fork syscall, like developer.gnome.org/glib/unstable/glib-Spawning-Processes.html Nov 28, 2011 at 8:23
  • I think that this in the end is only clear answer which just say "Remember that fork was invented very early in Unix". Despite nobody confirmed that, I believe that new function that would be more effective could be implemented that would do exactly what fork() does, except for extra memory / attribute cloning with only purpose to launch a new separate process which shares almost nothing with its parent.
    – Petr
    Mar 8, 2014 at 20:01
  • 1
    Well, there's only one way to proove this: dig into the *nix kernel, figure out fork's places to improve, and actually improve them. You can do it yourself, by the way. Mar 9, 2014 at 20:09
  • Windows also creates a new process by forking. The function is called ZwCreateProcess and in ntdll.dll. Once a clone is set up, the clone must empty its address space, load in the new binary code, hook up with the Win32 subsystem and execute main(). This makes process creation heavyweight. Jan 14, 2015 at 0:51
4

"fork()" was a brilliant innovation that solved a whole class of problems with a single API. It was invented at a time when multiprocessing was NOT common (and preceded the kind of multiprocessing you and I use today by about twenty years).

2
  • Err, multiprocessing had been going on since the 1950s actually.
    – user207421
    Jan 14, 2015 at 1:28
  • 1
    Brilliant? I would say a stupid one to (arguably) solve a particular tiny subset of spawning a new process - clone the existing one. In most cases you just need to launch a small helper process to do some small work for you and all you got is 'fork'? Ouch! So lame, never liked it. Cloning does make sense in many cases, but not here, trust me.
    – Sergey
    Feb 11, 2016 at 23:14
3

Historically, Unix was running on quite small systems not allowing for more than one process to run in RAM (they all ran in the same address space, no MMU was there). fork was simply swapping out the current process to disk (or other secondary storage) without bothering to swap in a different process. You could either continue running the in-memory copy, or use exec to load and continue with a different executable.

People got used to being able to set up a new work environment (open file descriptors, pipes and stuff) before calling exec, so fork stuck around.

2

Take a look at spawn and friends.

2
  • 2
    Remember that spawn is POSIX, while fork is pure Unix. Not to say that it can't be used, but for a pure Unix experience, you're stuck with fork-execve :)
    – Eli Iser
    Nov 28, 2011 at 6:36
  • 2
    Also, note that spawn uses fork (or clone) internally. There is nothing else in the kernel that would offer the needed functionality. Which means it's more user-friendly and obvious, but whatever is the overhead (copying page tables and descriptors), the overhead is the same.
    – Damon
    Nov 28, 2011 at 10:01
2

When fork creates a new process by copying the current process, it performs a copy-on-write. This means that the memory of the new process is shared with the parent process until it is changed. When the memory is changed, the memory gets copied to make sure each process has its own valid copy of the memory. When doing an execve right after forking, there is no copy of the memory, since the new process just loads a new executable, and thus a new memory space.

As to the question why this is done, I don't know for sure, but it seems to be part of the Unix-way - do one thing well. Instead of making a function that creates a new process and loads a new executable, the operation is split into two functions. This gives the developer maximum flexibility. Although I haven't used either function on its own yet...

1
  • It is done in hardware by the MMU by tagging the pages COW. Windows uses the same mechanism to start a new process. The system call underlying fork (clone) is very similar to the system call underlying CreateProcess (ZwCreateProcess), and you can in fact implement fork on top of ZwCreateProcess. Jan 14, 2015 at 0:58
2

So as the others said, fork is implemented to be very fast so that is not a problem. But why not a function like create_process()? The answer is: simplicity for flexibility. All system calls in unix are programmed to do only one thing. A function like create_process would do two things: create a process and loading a binary into that.

Whenever you try to parallelizing things you can use threads - or processes opened with fork(). In most cases you open n processes via fork() and then use an IPC-Mechanism for communicating and synchronising between these processes. Some IPC insists on having variables in global space.

Example with pipes:

  • Creating the pipe
  • Fork a child which inherits the pipe handle
  • The child closes the input side
  • The parent closes the output side

Impossible without fork()

Another important fact is that the whole Unix API has only a few functions. Every programmer could remember easily on used functions. But see the Windows API: Over thousands of function no one can ever remember.

So to sum up and say it again: simplicity for flexibility

4
  • 2
    While I agree with you that fork() can do things that "create_process()" couldn't I strongly disagree that even given that fork() was implemented to be very fast could ever make it faster than a function that would do exactly the same what fork() does except for memory copying. That would always save a bunch of CPU instructions, thus would be much faster.
    – Petr
    Mar 8, 2014 at 19:51
  • @Petr: loading a new process mostly makes fork()'s overhead insignificant by comparison.
    – ninjalj
    Mar 8, 2014 at 21:25
  • The cloning is done by the MMU by tagging the pages copy-on-write. It does not eat any CPU cycles. In fact, spawning threads is done with the same system call used to implement fork on Unix and Linux, and forking does not have higher overhead than spawning threads. It is less known that Windows also starts a new process by forking, though it is called ZwCreateProcess and is hidden in ntdll.dll. The overhead in CreateProcess vs. fork comes from having to empty and reinitialize the clone to start an empty process. Jan 14, 2015 at 0:44
  • "A function like create_process would do two things: create a process and loading a binary into that." Not necessarily. It could create a blank non-running process that could be manipulated by the parent process, and then when the set-up is done the actual executable code could be loaded by something similar to exec that is instead called by the parent.
    – Pharap
    Nov 22, 2022 at 11:05
2

This is a great question. I had to a dig a bit into the source to see exactly what was happening.

fork() creates a new process by duplicating the calling process.

Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.

The new process, referred to as the child, is an exact duplicate of the calling process (referred to as the parent). Except for:

  • The child has its own unique process ID, and this PID does not match the ID of any existing process group.
  • The child's parent process ID is the same as the parent's process ID.
  • The child does not inherit its parent's memory locks.
  • Process resource utilizations and CPU time counters are reset to zero in the child.
  • The child's set of pending signals is initially empty.
  • The child does not inherit semaphore adjustments from its parent.
  • The child does not inherit record locks from its parent.
  • The child does not inherit timers from its parent.
  • The child does not inherit outstanding asynchronous I/O operations from its parent, nor does it inherit any asynchronous I/O contexts from its parent.

Conclusion :

Main objective of fork is to divide the tasks of parents process into smaller subtasks without affecting unique task structure of parent. That is why fork clones the existing process.

Sources :

http://www.quora.com/Linux-Kernel/After-a-fork-where-exactly-does-the-childs-execution-start http://learnlinuxconcepts.blogspot.in/2014/03/process-management.html

3
  • 1
    +1 for digging out how precisely fork() works. However isn't there really any better way to start a new process than cloning existing? I just don't see any point in this. If you wanted to start new, separate process, why would you want to clone the existing process first?
    – Petr
    Mar 7, 2014 at 20:28
  • I have made changes to my answer in response to your comment. Mar 8, 2014 at 12:24
  • If you spawn a new process you will have to start it from main() and set everything up. This is also often the case with threads, which starts from their own threadproc, which subsequently have to decode the data supplied by the void pointer (its only argument). With fork there is no need to initialize anything. Jan 14, 2015 at 0:35
2

The other answers have done a good job of explaining why fork is faster than it would seem, and how it originally came to exist. But there's also a strong case to be made for keeping the fork+exec combo, and that's the flexibility it offers.

Often, when spawning a child process, there are preparatory steps to be taken before executing the child. For example: you might create a pair of pipes using pipe (a reader and a writer), then redirect the child process's stdout or stderr to the writer, or use the reader as the process's stdin — or any other file descriptor, for that matter. Or, you might want to set environment variables (but only in the child). Or set resource limits with setrlimit to restrict the amount of resources the child could use (without limiting the parent). Or change users with setuid/seteuid (without changing the parent). Etc etc.

Sure, you could do all of this with a hypothetical create_process function. But that's a lot of stuff to cover! Why not offer the flexibility of running fork, doing whatever you want to set up the child, then running exec?

Also, sometimes you don't actually need a child process at all. If your current program (or script) exists solely to do some of those setup steps, and the last thing it's ever going to do is run the new process, then why have two processes at all? You can use exec to just replace the current process, releasing your own memory and PID.

Forking also allows for some useful behaviour regarding read-only datasets. For example, you could have a parent process that collects and indexes a huge amount of data, then forks off child workers to perform traversals and calculations based on that data. The parent doesn't need to save it anywhere, the children don't need to read it, and you don't need to do any complex work with shared memory. (As an example: some databases use this as a means to have a child process dump the in-memory database to disk, without blocking the parent process.)

The above also includes any program that reads a configuration, a database, and/or a set of code files, then proceeds to fork off child processes to handle requests and make better use of multi-core CPUs. This includes webservers, but also web (or other) applications themselves, particularly if those applications spend a significant amount of start-up time just reading and/or compiling higher-level code.

Forking can also be a useful way to manage memory and avoid fragmentation, especially for higher-level languages that use automatic memory management (garbage collection) and don't have direct control over their memory layout. If your process briefly needs a large amount of memory for a particular operation, you can fork and perform that operation, then exit, freeing all memory you just allocated. By contrast, if you did the operation in the parent, you might have significant memory fragmentation that could persist for the duration of the process — not great for a long-running process.

And finally: once you accept that fork and exec both have their own uses, independent of each other, the question becomes — why bother creating a separate function that combines the two? It's been said that the Unix philosophy was to have its tools "do one thing and do it well". By giving you fork and exec as separate building blocks — and by making each as fast and efficient as possible — they allow for much more flexibility than a single create_process function would.

1

It is possible for fork() to be implemented with very little memory allocation, assuming the underlying implementation uses a copy-on-write addressing system. It is impossible for a create_process function to be implemented with that optimization.

1

The main reason to use fork is execution speed.

If as you suggested you started a new copy of the process with a set of parameters the new process would need to parse those parameters and repeat most of the processing the parent process had done. With "fork()" the a complete copy of the parent processes stack is available to the child immediately with everything parsed and formatted as it should be.

Also in most cases the program will be an ".so" or ".dll" so the executable instructions will not be copied only the stack and heap storage will be copied.

1

So, your main concern is: fork() leads to unnecessary memory copying.

The answer is: no, there's no memory waste. In short, fork() was born when the memory was very limited resource, so nobody would even think about wasting it like that.

Although each process has its own address space, there is no one-to-one mapping between physical memory page and virtual memory page of process. Instead, one page of physical memory can be mapped to several virtual pages (search for CPU TLB for further details).

So when you create new process with fork(), their virtual address spaces are mapped to the same physical memory pages. No memory copy is required. It also means that there is no duplicates of used libraries because their code sections are marked read-only.

The actual memory copying occurs only when parent or child process modifies some memory page. In that case new physical memory page is allocated and mapped to virtual address space of the process that modified the page.

2
  • 1
    What about CPU waste? Isn't this operation when some attributes of process are copied to new process just a bunch of extra instructions that don't need to be executed given that I know I will discard them anyway? I mean fork() makes a copy of process. It does copy of many attributes which are later overriden and that consumes some CPU that wouldn't need to be consumed, or not?
    – Petr
    Mar 8, 2014 at 19:55
  • Not so many attributes will be overriten. Such an overhead is acceptable Mar 9, 2014 at 20:14
0

Well in terms of paging/virtual memory there are techniques in which fork() doesn't always copy the entire address space of a process. There is copy on write where a forked process gets the same address space as its parent and then only copies a portion of the space that is changed (by either process).

0

You can think of this somewhat like spawning a thread in Windows, except that processes do not share resources except file handles, shared memory, and other things that are explicitly inheritable. So if you have a new task to do, you can fork and one process continues on its original job while the clone takes care of the new assignment.

If you want to do parallel computing, your processes can split itself into multiple clones right above the loop. Each of the clones does a subset of the computation while the parent waits for them to complete. The operating systems makes sure they can run in parallel. In Windows you would e.g. need to use OpenMP to get the same expressability.

If you need to read or a write from a file but cannot wait, you can just fork and your clone does the i/o while you continue on your original task. On Windows you might consider spawning threads or using overlapped i/o in many situations where a simple fork will do in Unix. In particular, processes do not have the same scability problems as threads. This is particularly true on 32 bit systems. Just forking is much more convinient than having to deal with the intricacies of overlapped i/o. While processes have their own memory space, threads live in the same, and thus there is a limit to how many threads you should consider to put into a 32 bit process. Making a 32 bit server app with fork is very simple, while making a 32 bit server app with threads can be a nightmare. And so if you were programming on 32 bit Windows you would have to resort to other solutions like overlapped i/o, which is a PITA to work with.

Because processes don't share global resources like threads to (e.g. a global lock in malloc) this is much more scalable. While threads will often block each other out, processes run independently.

On Unix because fork makes a copy-on-write clone of your process it is not more heavyweight than spawning a new thread in Windows.

If you deal with interpreted languages, where there typically is a global interpreter lock (Python, Ruby, PHP...), an OS which gives you the ability to fork is indispensable. Otherwise your ability to exploit multiple processors are much more limited.

Another thing is that there is a security isse here. Processes don't share memory space and cannot mess up each others internal details. This leads to higher stability. If you have a server which uses threads, a crash in one thread will take down the entire server application. With forking a crash will only take down the forked clone. This also makes error handling more simplified. It is often sufficient to let your forked clone abort as it makes no difference for the original app.

There is also a security issue. If a forked process is injected with malicious code it cannot further affect the parent. Modern web browsers make use of this e.g. to protect one tab from another. All of this is much more convinient to program if you have a fork system call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.