Skip to content

Process Creation

Creating a new process: fork()

  • The fork() system call creates a new process, the child, which is an almost exact duplicate of the calling process, the parent.
#include <unistd.h>
pid_t fork(void);
// In parent: returns process ID of child on success, or –1 on error;
// in successfully created child: always returns 0
  • The key point to understanding fork() is to realize that after it has completed its work, two processes exist, and, in each process, execution continues from the point where fork() returns.
  • The two processes are executing the same program text, but they have separate copies of the stack, data, and heap segments. The child’s stack, data, and heap segments are initially exact duplicates of the corresponding parts the parent’s memory. After the fork(), each process can modify the variables in its stack, data, and heap segments without affecting the other process

Explain

  • For the parent, fork() returns the process ID of the newly created child (to track via wait() system calls)
  • For the child, fork() returns 0. The child can obtain its own process ID using getpid(), and the process ID of its parent using getppid().
  • When a fork() is performed, the child receives duplicates of all of the parent’s file descriptors. These duplicates are made in the manner of dup(), which means that corresponding descriptors in the parent and the child refer to the same open file description

Example 1

#include <dbg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static int idata = 111; // ALlocated in data segment
//
int main(int argc, char *argv[]) {
int istack = 222; // Allocated in stack segment
pid_t childPid;
switch (childPid = fork()) {
case -1:
sentinel("fork");
case 0:
idata *= 3;
istack *= 3;
break;
default:
sleep(3); // Give child a chance to execute
break;
}
printf("PID=%ld %s idata=%d istack=%d\n", (long)getpid(),
(childPid == 0) ? "(child) " : "(parent)", idata, istack);
exit(EXIT_SUCCESS);
error:
return -1;
}

Example 2: file sharing between parent and child