How to Use the fork Function in C

Jinku Hu Feb 02, 2024
  1. Use the fork Function to Create a New Process in C
  2. Use One of the exec Functions to Execute a New Program in Child Process in C
How to Use the fork Function in C

This article will explain several methods of how to use fork function in C.

Use the fork Function to Create a New Process in C

The fork function is used to create a new process representing the caller process’s duplication. Note that the calling process is conventionally called a parent process and a newly created one - a child process. Even though we mentioned above that the child process is a duplicate of the parent, there are some differences like the child process has its own unique PID (full details about differences are listed on the fork manual page).

In the following example, we implement a simple scenario where fork is used to execute two processes concurrently. The first if statement checks whether an error code is returned and continues only if the fork was successful. The next if statement demonstrates how to structure code to be executed by concurrent processes.

The fork call is a bit unique compared to other functions as it returns twice when successful - in the parent process and the child - returning the PID of the child process in the parent and 0 value in the child. Note that we specify the conditions of the loop accordingly to distinguish different code paths for processes.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
  pid_t c_pid = fork();
  if (c_pid == -1) {
    perror("fork");
    exit(EXIT_FAILURE);
  }

  if (c_pid == 0) {
    printf("printed from child process - %d\n", getpid());
    exit(EXIT_SUCCESS);
  } else {
    printf("printed from parent process - %d\n", getpid());
    wait(NULL);
  }

  exit(EXIT_SUCCESS);
}

Output:

printed from parent process - 8485
printed from child process - 8486

Use One of the exec Functions to Execute a New Program in Child Process in C

One of the common cases for using the fork function is to execute a new program in the child process, which can be accomplished by adding one of the exec functions to the mix. In this case, we implemented a separate function called spawnChild that creates a new process and then calls execvp to execute the given program. We chose a widely available command line program - top to execute in the child process. Note that the parent process can choose to wait for the child process state changes using waitpid.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

pid_t spawnChild(const char* program, char** arg_list) {
  pid_t ch_pid = fork();
  if (ch_pid == -1) {
    perror("fork");
    exit(EXIT_FAILURE);
  }

  if (ch_pid == 0) {
    execvp(program, arg_list);
    perror("execve");
    exit(EXIT_FAILURE);
  } else {
    printf("spawned child with pid - %d\n", ch_pid);
    return ch_pid;
  }
}

int main(void) {
  int ret;
  const char* args[] = {"top", NULL, NULL};

  pid_t child;
  int wstatus;

  child = spawnChild("top", args);

  if (waitpid(child, &wstatus, WUNTRACED | WCONTINUED) == -1) {
    perror("waitpid");
    exit(EXIT_FAILURE);
  }

  exit(EXIT_SUCCESS);
}

Output:

printed from child process - 8486
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C Process