6

How exactly does fork() work?

The following code

#include <stdio.h>

int main (int argc, char const *argv[])
{
printf("Hi\n");
int i;
for(i = 1; i < argc; i++)
{
    printf("Argument %d is %s\n", i, argv[i]);
    fork();
    printf("Forked in for loop increment %d\n", i);
}


return 0;
}

gives the following output

/a.out hello world

Argument 1 is hello

Forked in for loop increment 1

Argument 2 is world

Forked in for loop increment 2

Forked in for loop increment 1

Argument 2 is world

Forked in for loop increment 2

Forked in for loop increment 2

What code does fork execute first, in general. I would like to know the principles of fork() rather than based on just this one example. I could have had multiple arguments on the command line.

2 Answers 2

9

fork is a system call, i.e. a library routine that calls into the kernel. When servicing a fork call, the kernel creates a new process that executes the same program as the process that called it. The new process starts executing as if it had called fork; the return value is different from the one in the parent, so you can distinguish the two.

The common idiom for invoking fork is:

pid_t pid = fork();

switch (pid) {
  case -1:
    /* an error occurred, i.e. no child process created */
    handle_error();
  case 0:
    /* a return value of 0 means we're in the child process */
    do_child_stuff();
    break;  // or _exit()
  default:
    /* we're in the parent; pid is the child's process id */
    do_parent_stuff();
}

How this works is: the OS makes a near-perfect copy of the process calling fork (the PID and some other values are different, but the memory contents start out practically the same and usually the same files are opened in both). The copy is commonly done using so-called copy-on-write (COW) semantics, so there's hardly any actual copying done until one of the processes starts assigning to variables.

8
  • So my print outs are misleading me. A fork() in a for loop is weird to right?
    – some_id
    Feb 15, 2011 at 22:50
  • 2
    The order of output in your program is nondeterministic. A fork in a loop isn't so strange (you may want to create some n number of worker processes), but a bare fork where child and parent run the same code is pretty rare. Most of the time, a fork is just preparation for a call to exec.
    – Fred Foo
    Feb 15, 2011 at 22:54
  • 1
    @Helium3 What is weird is code that doesn't store the return value of fork in a variable called something like childpid and then do different things depending on whether it is 0 (in the child), positive (in the parent), or negative (failure). This can happen in a loop or not.
    – Jim Balter
    Feb 16, 2011 at 0:07
  • How would one use these pids? In the switch above would one know what would execute because pid_t pid = fork(); returns the specific pid, or why would there be a possibility that the pid returned could be the child or parent? How does one use the pids as needed afterwards? Is it possible to use some library functions on a pid e.g. (taking a guess here) sleep() or kill(). Can forked processes create forked process recursively for a certain amount of needed processes and keep track of them from the main parent?
    – some_id
    Feb 16, 2011 at 0:26
  • @Helium3: please read the comments in the switch. If the pid is zero, we're in the child and we perform "child labor". Else we're in the parent and we (probably) control the child somehow, feed data to it, and eventually wait for it to exit. I've never seen recursive forking outside of a fork-bomb and don't see any use for it. It would only set up needless processes waiting for their children to perform work. A simple loop is simpler and more efficient.
    – Fred Foo
    Feb 16, 2011 at 0:32
3

Be aware that number of process will grow exponentially, so for 100 arguments we are talking about 1267650600228229401496703205376 processes. I hope you have a really strong PC :).

I will answer your comment here, it will maybe help you to understand the fork.

After each loop you will double the number of process. So after N loops you will end up with 2^N process. Or after 100 loops you will end up with that big number I gave you.

Btw, fork bombs are one of the most common DoS attacks around :)

3
  • It was an exaggeration. ;) how do you get to that number?
    – some_id
    Feb 15, 2011 at 22:59
  • Each argument doubles the amount of forked processes. So you'll end up with 2^n processes. For a long time most OS couldn't manage more than 2^16 processes at a time, due to the simple fact that the process id (PID) used to be a 16 bit number. And even if today's OS mostly use 32bit types for the PID, oftenly ther's a 2^16 limit in place. But one seldomly has more than 1000 processes spawned on a system on a time.
    – datenwolf
    Feb 16, 2011 at 0:03
  • Thanks for the info. @Klark: fork bombs link was interesting thanks.
    – some_id
    Feb 16, 2011 at 0:19

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.