Life Of A Process

published:

tags: [ #linux, #unix, #operating systems ]

Process creation in Linux and other *nix operating systems is a rather interesting topic. Let's dive in.

First things first - a process layout

In unix, a process looks something like the following in memory. process layout

The stack grows down as local variables are created and functions are called.

what happens when fork() is called

So to create a new process in unix, we call the fork() API. It duplicates the parent process into a new one (NOTE: optimizations techniques such as copy-on-write are also useful but covered in this article). The magical thing about this is that it returns twice: once in the context of the caller and once in the context of the child process. The copied process has the stack, BSS, data and dynamic regions of the parent. The text however is read-only and is shared. As a result when forking the code looks as follows:

if (fork() == 0) {
   /* the child process's thread executes here */
} else {
   /* the parent process's thread executes here */
}

The resulting process differs in some respects from the parent such as PID, file locks, alarms and more.

References

  • https://www.gnu.org/software/libc/manual/html_node/Processes.html
  • Operating Systems in Depth by Thomas W. Doeppner
  • https://unix.stackexchange.com/questions/31407/how-does-forking-affect-a-processs-memory-layout