Challenge, Easy,  on  ProgrammingLinux

Create a Process from Scratch Using Syscalls

In Linux, userspace processes cannot be created out of thin air. Process creation is performed using low-level system calls: fork() (which clones the calling process) and execve() (which replaces the process memory layout with a new executable program from disk).

When fork() is called, it returns twice: it returns 0 inside the newly created child process, and returns the numeric Process ID (PID) of the child to the parent process.

High-level overview of process execution hierarchy: bash spawning ./spawn, and ./spawn forking and execing a child process.

Overview of execution flow: bash spawns ./spawn, which in turn calls fork() and execve() to spawn a child process.

In this challenge, you will put process creation primitives into practice by writing a C program that calls fork() and execve(), compiles it with gcc, and retrieves the child PID.

Your task is to:

  1. Create a workspace directory named ~/exercise and navigate into it (mkdir -p ~/exercise && cd ~/exercise).
  2. Write a C program in ~/exercise (e.g., spawn.c) that spawns a child process using fork() and execve(), and prints the child process PID to standard output.
  3. Compile your C program using gcc into an executable binary inside ~/exercise.
  4. Run your compiled binary and enter the numeric Process ID (PID) of the spawned child process.
Hint 1: Required C Header Libraries

Include the necessary C standard headers for process handling:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
Hint 2: Understanding fork() Return Values

fork() returns twice:

  • In the parent process, fork() returns the PID of the newly created child (a positive integer).
  • In the child process, fork() returns 0.
#include <stdio.h>
#include <unistd.h>

int main(void) {
    pid_t pid = fork();
    if (pid == 0) {
        // Child process
    } else if (pid > 0) {
        printf("Child PID: %d\n", pid);
    }
    return 0;
}
Hint 3: Compiling and Running

Compile and execute your program inside ~/exercise:

gcc spawn.c -o spawn
./spawn