fork is a system call, that is, a library procedure that calls in the kernel. When servicing a fork call, the kernel creates a new process that runs the same program as the process it invoked. The new process starts as if it was calling fork ; the return value is different from the value in the parent, so you can distinguish between the two.
Common idiom for calling fork :
pid_t pid = fork(); switch (pid) { case -1: handle_error(); case 0: do_child_stuff(); break;
How it works: The OS creates an almost perfect copy of the process that calls fork (PID and some other values ββare different, but the contents of the memory start almost the same, and usually the same files open in both). Copying is usually performed using the so-called copy-on-write (COW) semantics, so there is practically no real copying until one of the processes begins to assign to variables.
Fred foo
source share