How to Fork a Process in C

Wed, Jul 3, 2019

Read in 2 minutes

Forking is one of the things you can do by just doing system calls. We use two system calls in the following code. The fork call, which (surprise) forks the process, and the wait call which (you guessed it) waits for a process. (The wait call actually blocks the main process until any child process returns, that is why we put it in a while loop as soon as wait returns 0 there are no more child processes to wait for.

When forking you need to know one perculiar thing - your code runs from the point of the fork call in two different processes. This means that you need to somehow know whether you are in a the child or the parent when moving along. This is what the child_pid variable tells you. If this value is zero, you are in the child. Otherwise it returns the PID (process id) of the child process. (You could use that PID to e.g. kill the child before it finishes).

To make this demo complete - I have let the child processes sleep for five seconds. Otherwise the program would just print a lot of text and exit in no time.

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
  pid_t child_pid, wpid;
  int status = 0;

  int count = 4;

  // Parent ; before any forks

  for (int id=0; id<count; id++) {
    if ((child_pid = fork()) == 0) {
      printf("Child %d started\n", id);

    } else {
      printf("Started child with PID %d\n", child_pid);

  while ((wpid = wait(&status)) > 0);

  printf("All children stopped\n");

compile it with gcc fork.c -o forker and run it with ./forker

See Also

How to Fork a Process in Ruby

Thu, Jul 4, 2019

Read more →

How to Write to a file in C

Mon, Nov 30, 2015

Read more →

How to Write a TCP Echo Server in C

Fri, Aug 21, 2015

Read more →

How to Read from stdin in C

Wed, Aug 12, 2015

Read more →

How to Read a file in C

Tue, Aug 11, 2015

Read more →