Skip to content

Process Examples

This section contains examples related to process management in C. These examples demonstrate various aspects of process creation, management, and communication in Unix-like systems. Below is a list of the source files with descriptions and links to their content.

File Name Description Link
process_01.c Demonstrates the use of the fork() system call to create a child process process_01.c
process_02.c Illustrates how a variable's value changes independently in the parent and child processes process_02.c
process_03.c Demonstrates the use of fork() to create a child process and uses sleep() to block both parent and child processes for a specified duration process_03.c
process_04a.c Clones a process using fork() and gets a zombie process_04a.c
process_04b.c Demonstrates the creation of an orphan process by cloning a process using fork() and having the parent process terminate before the child process. process_04b.c
process_05.c Demonstrates the use of fork() to create a child process, with the parent process waiting for the child process to finish and then checking its exit status process_05.c
process_06a.c Shows the use of fork() to create a child process, which then executes a new program (ls command) using execl(), while the parent process waits for the child to finish process_06a.c
process_06b.c Shows the use of fork() to create a child process, which then executes a new program (gnuplot) using execlp(), while the parent process waits for the child to finish. process_06b.c
process_07.c The child creates its own process group with setpgid(0, 0) (the parent makes the same call, to avoid a race), then the parent sends SIGTERM to the whole group with kill(-pgid, SIGTERM) (course, chapter "Signaux", slide "Groupes de processus") process_07.c
process_08.c Creates two child processes using fork(). Each child executes the GTK application ./bin/moving_window with different parameters using execv() (a path is given: no PATH search), while the parent waits for both with waitpid() (run it from 1_process/; needs GTK 3) process_08.c
process_09.c Creates four child processes using fork(). Each child executes an application (Firefox twice, Gedit, VLC) with execvp(args[0], args): the program is searched in PATH; the parent waits for all of them process_09.c
test_thread.c This program prints the process ID and the main thread ID of the executing program test_thread.c
update_w1.sh Bash script that sends SIGUSR1 and SIGUSR2 every minute to the two moving_window processes whose PIDs are given (update_w1.sh PID1 PID2); stops when a window is closed update_w1.sh
moving_window.c GTK window that takes a predefined color on SIGUSR1 or SIGUSR2 (the handler only sets a flag, read by a GTK timer); used by process_08.c and update_w1.sh; needs GTK 3 moving_window.c
fork_memoire.c After fork(), the child modifies a copy of a variable: parent and child memories are distinct (course, chapter "Processus", exercise 1) fork_memoire.c
exec_variantes.c The exec family side by side: execl, execlp, execv, execvp, execle, execve, then three classic mistakes (forgotten argv[0], "ls -ld" as a program name, execl without a path); the parent displays each exit code, or the signal that killed the child (course, chapter "Processus", exercise 4; the slides use ls -l) exec_variantes.c
lancer.c Minimal launcher: fork() + execvp() + waitpid(), then decodes the child's status with WIFEXITED/WIFSIGNALED and displays "code de sortie" or "tué par le signal", as the slide (course, chapter "Processus") lancer.c
zombie.c The child exits while the parent waits for a key press before waitpid(): observe the zombie with ps (course, chapter "Processus", exercise 3) zombie.c
attendre.h Helper used by exec_variantes.c, fork_memoire.c, lancer.c and zombie.c: waitpid() restarted on EINTR attendre.h

Sources

src/attendre.h

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @file attendre.h
 *
 * @brief Fonction attendre() : waitpid() bloquant sur un enfant précis,
 * relancé si un signal l'interrompt (EINTR).
 */

#ifndef ATTENDRE_H
#define ATTENDRE_H

#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

/* Attente bloquante d'un enfant précis ; recommencer si un signal interrompt. */
static int attendre(pid_t enfant, int *status)
{
    pid_t resultat;
    do {
        resultat = waitpid(enfant, status, 0);
    } while (resultat == -1 && errno == EINTR);
    return resultat == -1 ? -1 : 0;
}

#endif
src/exec_variantes.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "attendre.h"

/**
 * @file exec_variantes.c
 *
 * @brief Les fonctions de la famille exec, côte à côte : chaque variante est
 * lancée dans un enfant, puis le parent affiche le code de sortie.
 *
 * - l / v : arguments en liste ou en tableau ;
 * - p     : recherche dans le PATH (sinon, un chemin) ;
 * - e     : environnement fourni.
 * Les trois dernières variantes sont des erreurs classiques, volontaires.
 *
 * Cours, chapitre "Processus", diapositives "La même commande, quatre
 * écritures" et "Les erreurs classiques avec exec" : les diapositives
 * utilisent ls -l /tmp ; ici, ls -ld /tmp n'affiche qu'une ligne.
 */

extern char **environ;

/** Le code de l'enfant : une variante d'exec par numéro. */
static void executer_variante(int numero)
{
    char *args[] = {"ls", "-ld", "/tmp", NULL};
    char *env_vide[] = {NULL};

    switch (numero) {
    case 1: /* l : liste + chemin */
        execl("/bin/ls", "ls", "-ld", "/tmp", (char *)NULL);
        break;
    case 2: /* lp : liste + PATH */
        execlp("ls", "ls", "-ld", "/tmp", (char *)NULL);
        break;
    case 3: /* v : tableau + chemin */
        execv("/bin/ls", args);
        break;
    case 4: /* vp : tableau + PATH */
        execvp(args[0], args);
        break;
    case 5: /* le : liste + chemin + environnement (vide ici) */
        execle("/usr/bin/env", "env", (char *)NULL, env_vide);
        break;
    case 6: /* ve : tableau + chemin + environnement (celui du parent) */
        execve("/bin/ls", args, environ);
        break;
    case 7: /* ERREUR : argv[0] oublié, "bonjour" devient argv[0] */
        execlp("echo", "bonjour", "le monde", (char *)NULL);
        break;
    case 8: /* ERREUR : "ls -ld" n'est pas un nom de programme */
        execlp("ls -ld", "ls -ld", (char *)NULL);
        break;
    default: /* ERREUR : sans p, "ls" est un chemin relatif au dossier courant */
        execl("ls", "ls", (char *)NULL);
        break;
    }
    perror("exec"); /* atteint seulement si exec a échoué */
    _exit(127);
}

/** Crée un enfant pour une variante, l'attend et affiche son code de sortie. */
static void lancer_variante(int numero, const char *titre)
{
    int status;
    pid_t pid;

    printf("\n--- %d. %s\n", numero, titre);
    fflush(stdout); /* rien à dupliquer dans l'enfant */
    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    if (pid == 0) {
        executer_variante(numero);
    }
    if (attendre(pid, &status) == -1) {
        perror("waitpid");
        exit(EXIT_FAILURE);
    }
    if (WIFEXITED(status)) {
        printf("    code de sortie : %d\n", WEXITSTATUS(status));
    } else if (WIFSIGNALED(status)) {
        printf("    tué par le signal %d\n", WTERMSIG(status));
    }
}

int main(void)
{
    lancer_variante(1, "execl(\"/bin/ls\", \"ls\", \"-ld\", \"/tmp\", NULL)");
    lancer_variante(2, "execlp(\"ls\", \"ls\", \"-ld\", \"/tmp\", NULL)");
    lancer_variante(3, "execv(\"/bin/ls\", args)");
    lancer_variante(4, "execvp(args[0], args)");
    lancer_variante(5, "execle(\"/usr/bin/env\", \"env\", NULL, env_vide)  : n'affiche rien");
    lancer_variante(6, "execve(\"/bin/ls\", args, environ)");
    lancer_variante(7, "ERREUR execlp(\"echo\", \"bonjour\", \"le monde\", NULL)");
    lancer_variante(8, "ERREUR execlp(\"ls -ld\", \"ls -ld\", NULL)");
    lancer_variante(9, "ERREUR execl(\"ls\", \"ls\", NULL)");
    return EXIT_SUCCESS;
}
src/fork_memoire.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "attendre.h"

/**
 * @file fork_memoire.c
 *
 * @brief Après fork(), le parent et l'enfant ont chacun leur propre copie
 * de la mémoire : modifier x dans l'enfant ne change pas x dans le parent.
 */

int main(void)
{
    int x = 10;
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if (pid == 0) {
        x = 20;
        printf("enfant : x = %d\n", x);
        return EXIT_SUCCESS;
    }
    printf("parent : x = %d\n", x);
    int status;
    if (attendre(pid, &status) == -1) {
        perror("waitpid");
        return EXIT_FAILURE;
    }
    return WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE;
}
src/lancer.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "attendre.h"

/**
 * @file lancer.c
 *
 * @brief Lance une commande dans un processus enfant (fork() + execvp()),
 * attend sa fin et affiche son état de terminaison.
 */

int main(int argc, char *argv[])
{
    if (argc < 2) {
        fprintf(stderr, "Usage : %s commande [arguments...]\n", argv[0]);
        return EXIT_FAILURE;
    }
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if (pid == 0) {
        execvp(argv[1], &argv[1]);
        perror("execvp");
        _exit(127);
    }
    int status;
    if (attendre(pid, &status) == -1) {
        perror("waitpid");
        return EXIT_FAILURE;
    }
    if (WIFEXITED(status)) {
        int code = WEXITSTATUS(status);
        printf("code de sortie : %d\n", code);
        return code;
    }
    if (WIFSIGNALED(status)) {
        printf("tué par le signal %d\n", WTERMSIG(status));
    }
    return EXIT_FAILURE;
}
src/moving_window.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _POSIX_C_SOURCE 200809L /* sigaction() with -std=c11 */

#include <gtk/gtk.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h> /* getpid() */

/**
 * @file moving_window.c
 *
 * @brief This program creates a GTK window that changes its background 
 * color in response to SIGUSR1 and SIGUSR2 signals. It demonstrates 
 * inter-process communication using UNIX signals and GTK for GUI.
 *
 * The program is a GTK-based application that displays a window with 
 * a specified initial color and position. It sets up signal handlers for
 * SIGUSR1 and SIGUSR2. When these signals are received, the background 
 * color of the window changes to predefined colors (color1 and color2).
 * Additionally, the program demonstrates signal handling in a GUI
 * application (the handler only sets a flag, read by a GTK timer) and
 * basic GTK window creation and manipulation. This example is useful for
 * understanding how to integrate system-level signal handling with
 * graphical user interfaces in C.
 */

GdkRGBA initial_color;
GdkRGBA color;
GtkWidget *window;

volatile sig_atomic_t sigusr1_received = 0;
volatile sig_atomic_t sigusr2_received = 0;
double color1[4] = {0.28, 0.26, 0.12, 1.0};
double color2[4] = {0.01, 0.19, 0.19, 1.0};

void change_color(double new_color[]) {
    color.red = new_color[0];
    color.green = new_color[1];
    color.blue = new_color[2];
    color.alpha = new_color[3];

    gtk_widget_override_background_color(window, GTK_STATE_FLAG_NORMAL, &color);
    gtk_widget_queue_draw(window);
}

static gboolean check_sigusr1_received(gpointer data) {
    (void) data;
    if (sigusr1_received) {
        /* Reset the flag */
        sigusr1_received = 0;

        change_color(color1);
    }

    return TRUE;  /* Continue checking */
}

static gboolean check_sigusr2_received(gpointer data) {
    (void) data;
    if (sigusr2_received) {
        /* Reset the flag */
        sigusr2_received = 0;

        change_color(color2);
    }

    return TRUE;  /* Continue checking */
}

static void handle_sigusr1(int signum) {
    (void) signum;
    sigusr1_received = 1;
}

static void handle_sigusr2(int signum) {
    (void) signum;
    sigusr2_received = 1;
}

int main(int argc, char *argv[]) {
    GtkWidget *label;
    char pid_text[100];

    /* Set up SIGUSR1 and SIGUSR2 signal handlers using sigaction */
    struct sigaction sa1;
    struct sigaction sa2;

    sa1.sa_handler = handle_sigusr1; /* Pointer to the signal handler function 1 */
    sigemptyset(&sa1.sa_mask); /* Clear any blocked signals during the execution of the signal handler */
    sa1.sa_flags = 0;

    if (sigaction(SIGUSR1, &sa1, NULL) == -1) {
        perror("Error setting up sigaction for SIGUSR1");
        return EXIT_FAILURE;
    }

    sa2.sa_handler = handle_sigusr2; /* Pointer to the signal handler function 2 */
    sigemptyset(&sa2.sa_mask); /* Clear any blocked signals during the execution of the signal handler */
    sa2.sa_flags = 0;

    if (sigaction(SIGUSR2, &sa2, NULL) == -1) {
        perror("Error setting up sigaction for SIGUSR2");
        return EXIT_FAILURE;
    }

    /* Initialize GTK */
    gtk_init(&argc, &argv);

    /* Check if we have enough arguments */
    if (argc != 4) {
        g_print("Usage: %s <x-pos> <y-pos> <color>\nExample color formats: '#RRGGBB', 'rgb(r,g,b)', 'rgba(r,g,b,a)'\n", argv[0]);
        return EXIT_FAILURE;
    }

    int x_pos = atoi(argv[1]);
    int y_pos = atoi(argv[2]);
    const char *color_name = argv[3];

    /* Set up a timeout function to check the signal_received flag every 100ms */
    g_timeout_add(100, check_sigusr1_received, NULL);
    g_timeout_add(100, check_sigusr2_received, NULL);

    /* Create a new window */
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(window), "GTK Position and Color");
    gtk_window_set_default_size(GTK_WINDOW(window), 200, 200);
    gtk_window_move(GTK_WINDOW(window), x_pos, y_pos);

    /* Set the background color */
    if (gdk_rgba_parse(&initial_color, color_name)) {
        color = initial_color;
        gtk_widget_override_background_color(window, GTK_STATE_FLAG_NORMAL, &color);
    } else {
        g_print("Failed to parse color: %s\n", color_name);
        return EXIT_FAILURE;
    }

    /* Create a label with the PID and add it to the window */
    snprintf(pid_text, sizeof(pid_text), "%ld", (long) getpid());
    label = gtk_label_new(pid_text);
    gtk_container_add(GTK_CONTAINER(window), label);

    /* Connect the close event */
    g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

    /* Show the window */
    gtk_widget_show_all(window);

    /* Main GTK loop */
    gtk_main();

    return EXIT_SUCCESS;
}
src/process_01.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <unistd.h>    /* fork() */
#include <stdio.h>     /* printf() and perror() */
#include <stdlib.h>    /* exit() */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h>  /* wait() */

/**
 * @file process_01.c
 * @brief A simple program that demonstrates the use of the fork() system call
 * to create a child process. 
 *
 * It separates the behavior of the parent and child processes into different 
 * functions, printing their respective process IDs and executing distinct 
 * instructions.
 */

/**
 * @brief Handles a fatal error and exit. 
 *
 * It displays the given error message, then exits with EXIT_FAILURE.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the parent process.
 * @param child_pid The PID of the child process.
 */
void manage_parent(pid_t child_pid) {
    printf("Parent process (PID %ld)\n", (long) getpid());
    printf("My child's PID is %ld\n", (long) child_pid);
    printf("Instructions of parent process...\n");
    if (wait(NULL) == -1) { /* Wait for child to exit to prevent zombie process */
        perror("wait");
    }
}

/**
 * @brief Manages the child process.
 */
void manage_child(void) {
    printf("Child process (PID %ld)\n", (long) getpid());
    printf("My parent's PID is %ld\n", (long) getppid());
    printf("Instructions of child process...\n");
}

int main(void) {
    pid_t pid;

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("Error [fork()]");
    }
    if (pid > 0) {
        manage_parent(pid);
    } else {
        manage_child();
    }

    return EXIT_SUCCESS;
}
src/process_02.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* fork() */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>  /* wait() */

/**
 * @file process_02.c
 *
 * @brief This program demonstrates process cloning using fork() and explores
 * how a variable's value changes independently in the parent and child 
 * processes.
 */

/**
 * @brief Handles a fatal error and exit. 
 *
 * It displays the given error message, then exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the parent process by modifying value of the given parameter.
 * @param parameter Pointer to the integer to modify.
 */
void manage_parent(int *parameter) {
    printf("Parent process (PID %ld) begins...\n", (long) getpid());
    *parameter = 10;
    if (wait(NULL) == -1) {  /* Wait for the child process to exit */
        perror("wait");
    }
    printf("Parent process (PID %ld) ends with variable: %d\n", (long) getpid(), *parameter);
}

/**
 * @brief Manages the child process by modifying value of the given parameter.
 * @param parameter Pointer to the integer to modify.
 */
void manage_child(int *parameter) {
    printf("Child process (PID %ld) begins...\n", (long) getpid());
    *parameter = 20;
    printf("Child process (PID %ld) ends with variable: %d\n", (long) getpid(), *parameter);
}

int main(void) {
    pid_t pid;
    int own_variable = 0;

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("Error [fork()]");
    }

    if (pid > 0) {
        manage_parent(&own_variable);
    } else {
        manage_child(&own_variable);
    }

    return EXIT_SUCCESS;
}
src/process_03.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* fork() and sleep() */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>  /* wait() */

/**
 * @file process_03.c
 *
 * @brief This program demonstrates the use of fork() to create a child process
 * and uses sleep() to block both parent and child processes for a specified 
 * duration.
 */

#define DURATION 5

/**
 * @brief Handles a fatal error and exit. 
 *
 * It displays the given error message, then exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the parent process. 
 *
 * The parent process is blocked during \em DURATION seconds and waits for his
 * child.
 */
void manage_parent(pid_t child_pid) {
    int status;

    printf("Parent process (PID %ld)\n", (long) getpid());
    printf("Parent will be blocked during %d seconds...\n", DURATION);

    sleep(DURATION);

    printf("Parent has finished to sleep.\n");
    if (waitpid(child_pid, &status, 0) == -1) {
        handle_fatal_error_and_exit("Error [waitpid()]");
    }
    if (WIFEXITED(status)) {
        printf("Child process exited with code %d\n", WEXITSTATUS(status));
    }
}

/**
 * @brief Manages the child process. 
 *
 * The child process is blocked during \em DURATION seconds.
 */
void manage_child(void) {
    printf("Child process (PID %ld)\n", (long) getpid());
    printf("Child will be blocked during %d seconds...\n", DURATION);
    sleep(DURATION);
    printf("Child has finished to sleep.\n");
}

int main(void) {
    pid_t pid;

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("Error [fork()]");
    }

    if (pid > 0) {
        manage_parent(pid);
    } else {
        manage_child();
    }

    return EXIT_SUCCESS;
}
src/process_04a.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* fork() and sleep() */
#include <sys/types.h> /* pid_t */

/**
 * @file process_04a.c
 *
 * @brief A simple program that clones a process using the fork() primitive,
 * but without waiting child process, which then becomes a zombie!
 */

#define DURATION 5

/**
 * @brief Handles a fatal error and exit. 
 *
 * It displays the given error message, then exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the parent process. 
 *
 * The parent process does not wait for its child: once the child has
 * terminated, it stays a zombie until the parent itself terminates.
 */
void manage_parent(void) {
    printf("Parent process (PID %ld)\n", (long) getpid());
    printf("Parent does not wait for the child (observe it with: ps -o pid,ppid,stat,comm).\n");
    /* Allow time to observe the zombie state */
    sleep(15);
    printf("Parent terminating: the zombie child is adopted by init (or a subreaper), which reaps it.\n");
}

/**
 * @brief Manages the child process. 
 *
 * The child process is blocked during \em DURATION seconds.
 */
void manage_child(void) {
    printf("Child process (PID %ld)\n", (long) getpid());
    printf("Child will be blocked during %d seconds...\n", DURATION);
    sleep(DURATION);
    printf("Child has finished to sleep.\n");
}

int main(void) {
    pid_t pid;

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("Error [fork()]");
    }

    if (pid > 0) {
        manage_parent();
    } else {
        manage_child();
    }

    return EXIT_SUCCESS;
}
src/process_04b.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* fork() and sleep() */
#include <sys/types.h> /* pid_t */

/**
 * @file process_04b.c
 *
 * A simple program that clones a process using the fork() primitive, and
 * where the parent process dies before his child. The child process becomes
 * an orphan and is adopted by init (or by a subreaper).
 */

#define DURATION 20

/**
 * @brief Handles a fatal error and exit. 
 *
 * It displays the given error message, then exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the parent process. 
 *
 * The parent process prints its PID and then exits, leaving the child
 * process orphaned.
 */
void manage_parent(void) {
    printf("Parent process (PID %ld)\n", (long) getpid());
    exit(EXIT_SUCCESS); /* Explicit exit to simulate the parent dying */
}

/**
 * @brief Manages the child process. 
 *
 * The child process is blocked during DURATION seconds and then checks its
 * parent.
 */
void manage_child(void) {
    printf("Child process (PID %ld)\n", (long) getpid());
    printf("Child will be blocked during %d seconds...\n", DURATION);

    sleep(DURATION);

    printf("Child has finished to sleep.\n");
    printf("The PID of my parent is %ld. I am an orphan.\n", (long) getppid());
}

int main(void) {
    pid_t pid;

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("Error [fork()]");
    }

    if (pid > 0) {
        manage_parent();
    } else {
        manage_child();
    }

    return EXIT_SUCCESS;
}
src/process_05.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* fork() and sleep() */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>  /* wait() */

/**
 * @file process_05.c
 *
 * @brief A simple program that clones a process using the fork() primitive. 
 * The parent is waiting for his child to finish.
 */

#define DURATION 20

/**
 * @brief Handles a fatal error and exit. 
 *
 * It displays the given error message, then exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the parent process. 
 *
 * The parent is waiting for his child to exit.
 */
void manage_parent(void) {
    pid_t child;
    int status;

    printf("Parent process (PID %ld) is waiting for the child to finish.\n", (long) getpid());
    child = wait(&status);
    if (child == -1) {
        handle_fatal_error_and_exit("Error [wait()]");
    }
    if (WIFEXITED(status)) {
        printf("Parent (PID %ld): Child (PID %ld) has finished with exit code: %d\n",
               (long) getpid(), (long) child, WEXITSTATUS(status));
    }
}

/**
 * @brief Manages the child process, simulating work by sleeping.
 */
void manage_child(void) {
    printf("Child process (PID %ld) starts and will be blocked for %d seconds.\n", (long) getpid(), DURATION);
    sleep(DURATION);
    printf("Child (PID %ld) has finished sleeping. My parent's PID is %ld.\n", (long) getpid(), (long) getppid());
}

int main(void) {
    pid_t pid;

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("Error [fork()]");
    }

    if (pid > 0) {
        manage_parent();
    } else {
        manage_child();
    }

    return EXIT_SUCCESS;
}
src/process_06a.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* fork(), execl() and _exit() */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>  /* wait() */

/**
 * @file process_06a.c
 *
 * @brief Demonstrates process cloning using fork() and overlaying the child
 * with a new program using execl().
 */

/**
 * @brief Handles a fatal error and exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the parent process by waiting for the child to exit.
 */
void manage_parent(void) {
    pid_t child;
    int status;

    printf("Parent process (PID %ld) waiting for the child.\n", (long) getpid());
    child = wait(&status);
    if (child == -1) {
        handle_fatal_error_and_exit("Error [wait()]");
    }
    if (WIFEXITED(status)) {
        printf("Parent (PID %ld): Child (PID %ld) finished with exit code: %d\n", (long) getpid(), (long) child, WEXITSTATUS(status));
    }
}

/**
 * @brief Manages the child process, replaces it with the 'ls' command.
 */
void manage_child(void) {
    const char *path = "/bin/ls";
    const char *command = "ls";
    const char *arguments = "-al";

    printf("Child process (PID %ld) will execute ls command.\n", (long) getpid());
    fflush(stdout); /* the stdio buffer would be lost by execl() */
    execl(path, command, arguments, (char *) NULL);

    /* If execl() returns, there was an error */
    perror("Error executing execl");
    _exit(127); /* not exit(): do not flush the stdio buffers inherited from the parent */
}

int main(void) {
    pid_t pid;

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("Error [fork()]");
    }

    if (pid > 0) {
        manage_parent();
    } else {
        manage_child();
    }

    return EXIT_SUCCESS;
}
src/process_06b.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* fork(), execlp() and _exit() */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>  /* wait() */

/**
 * @file process_06b.c
 *
 * @brief Demonstrates cloning a process with fork() and replacing the
 * child with gnuplot using execlp().
 */

/**
 * @brief Handles a fatal error and exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the parent process by waiting for the child to exit.
 */
void manage_parent(void) {
    pid_t child;
    int status;

    printf("Parent process (PID %ld) waiting for the child.\n", (long) getpid());
    child = wait(&status);
    if (child == -1) {
        handle_fatal_error_and_exit("Error [wait()]");
    }
    if (WIFEXITED(status)) {
        printf("Parent (PID %ld): Child (PID %ld) finished with exit code: %d\n", (long) getpid(), (long) child, WEXITSTATUS(status));
    }
}

/**
 * @brief Manages the child process, replaces it with the gnuplot command.
 */
void manage_child(void) {
    const char *program = "gnuplot"; /* a name searched in PATH (the p of execlp) */
    const char *command = "gnuplot";
    const char *argument1 = "-persist";
    const char *argument2 = "resources/command.gp";

    printf("Child process (PID %ld) will execute Gnuplot.\n", (long) getpid());
    fflush(stdout); /* the stdio buffer would be lost by execlp() */
    execlp(program, command, argument1, argument2, (char *) NULL);

    /* If execlp() returns, there was an error */
    perror("Failed to run Gnuplot using execlp()");
    _exit(127);
}

int main(void) {
    pid_t pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("Error [fork()]");
    }

    if (pid > 0) {
        manage_parent();
    } else {
        manage_child();
    }

    return EXIT_SUCCESS;
}
src/process_07.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _POSIX_C_SOURCE 200809L /* kill(), setpgid() with -std=c11 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* getpid(), getpgrp(), setpgid() and pause() */
#include <signal.h>    /* kill() and SIGTERM */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>  /* wait(), WIFEXITED and WEXITSTATUS */

/**
 * @file process_07.c
 *
 * @brief A simple program about a process and its group.
 *
 * The child leaves the group of its parent with setpgid(0, 0): it becomes the
 * leader of a new group whose PGID is its PID. The parent makes the same call
 * (setpgid(pid, pid)), so that the group exists whoever runs first, then sends
 * SIGTERM to the whole group with kill(-pgid, SIGTERM) (killpg(pgid, SIGTERM)
 * does the same, but is an XSI extension).
 *
 * Course "Operating Systems", chapter "Signaux", slide "Groupes de processus".
 */

/**
 * @brief Handles a fatal error and exits.
 * @param msg The error message to display before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Manages the parent process: displays its group, sends SIGTERM to
 * the group of the child, then waits for it.
 */
void manage_parent(pid_t pid) {
    pid_t child;
    int status;

    printf("Parent process: PID=%ld, Group ID=%ld\n", (long) getpid(), (long) getpgrp());

    /* Same call as in the child: no race on who runs first.
       EACCES: the child has already called exec (not the case here). */
    if (setpgid(pid, pid) == -1) {
        perror("setpgid (parent)");
    }
    sleep(1); /* let the child display its new group */

    printf("Parent: SIGTERM to the group %ld\n", (long) pid);
    if (kill(-pid, SIGTERM) == -1) { /* -pid: the whole group of PGID pid */
        handle_fatal_error_and_exit("kill");
    }

    child = wait(&status);
    if (child == -1) {
        handle_fatal_error_and_exit("wait");
    }

    if (WIFEXITED(status)) {
        printf("Parent (PID %ld): Child (PID %ld) exited with code %d\n",
                (long) getpid(), (long) child, WEXITSTATUS(status));
    } else if (WIFSIGNALED(status)) {
        printf("Parent (PID %ld): Child (PID %ld) killed by signal %d\n",
                (long) getpid(), (long) child, WTERMSIG(status));
    }
}

/**
 * @brief Manages the child process: creates its own group, then waits.
 */
void manage_child(void) {
    printf("Child process: PID=%ld, Group ID=%ld\n", (long) getpid(), (long) getpgrp());

    /* New group, led by the child: PGID = PID of the child */
    if (setpgid(0, 0) == -1) {
        handle_fatal_error_and_exit("setpgid (child)");
    }
    printf("Child process: PID=%ld, new Group ID=%ld\n", (long) getpid(), (long) getpgrp());

    fflush(stdout); /* killed by SIGTERM: an unflushed stdio buffer would be lost */
    pause();        /* waits for the SIGTERM of its parent */
}

int main(void) {
    pid_t pid;

    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("Fork failed: unable to create child process");
    }

    if (pid > 0) {
        manage_parent(pid);
    } else {
        manage_child();
    }

    return EXIT_SUCCESS;
}
src/process_08.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* fork(), execv() and _exit() */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>  /* waitpid() */

/**
 * @file process_08.c
 *
 * A simple program about a process that executes Gtk windows through its children.
 */

/* Built by the Makefile in bin/; run this program from 1_process/ */
static char *path = "./bin/moving_window";

/*
 * This block will be executed by the first child
 */
void manage_child1(void) {
    /* Arguments for the GTK application */
    char *args[] = {"moving_window", "100", "100", "#5bccc9", NULL};

    /* Execute the GTK application: path is given, no PATH search, so execv() */
    execv(path, args);

    /* If execv() fails */
    perror("execv failed for child 1");
    _exit(127);
}

/*
 * This block will be executed by the second child
 */
void manage_child2(void) {
    /* Arguments for the GTK application */
    char *args[] = {"moving_window", "350", "100", "#bca850", NULL};

    /* Execute the GTK application */
    execv(path, args);

    /* If execv() fails */
    perror("execv failed for child 2");
    _exit(127);
}

int main(void) {
    pid_t pid1, pid2;

    /* First fork to create the first child */
    pid1 = fork();

    if (pid1 == -1) {
        perror("Fork failed");
        exit(EXIT_FAILURE);
    }

    if (pid1 == 0) {
        manage_child1(); /* never returns: exec or _exit() */
    }

    /* Second fork to create the second child (only the parent gets here) */
    pid2 = fork();
    if (pid2 == -1) {
        perror("Fork failed");
        exit(EXIT_FAILURE);
    }
    if (pid2 == 0) {
        manage_child2(); /* never returns */
    }

    /* Parent process waits for both children to finish */
    if (waitpid(pid1, NULL, 0) == -1) {
        perror("waitpid");
    }
    if (waitpid(pid2, NULL, 0) == -1) {
        perror("waitpid");
    }

    return EXIT_SUCCESS;
}
src/process_09.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>

/**
 * @file process_09.c
 *
 * @brief Another simple program that uses execvp() to executes different
 * applications with arguments.
 */

/**
 * Launches the given program with its given arguments.
 *
 * @param args The program name (args[0], searched in PATH) followed by its
 *             arguments, terminated by NULL.
 */
void launch_process(char *const args[]) {
    pid_t pid = fork();
    if (pid == 0) {
        execvp(args[0], args); /* args[0] is searched in PATH */
        perror("execvp failed");
        _exit(127);
    } else if (pid == -1) {
        perror("fork failed");
        exit(EXIT_FAILURE);
    }
}

int main(void) {
    char *firefox_args1[] = {"firefox", "-url", "https://foad.ensicaen.fr",
                             "-new-tab", "-url", "https://gitlab.ecole.ensicaen.fr", NULL};
    char *firefox_args2[] = {"firefox", "--search", "chatgpt", NULL};
    char *gedit_args[] = {"gedit", "pointeurs_et_cie1.c", NULL};
    char *vlc_args[] = {"vlc", "resources/test_pattern.mp4", NULL};

    /* child 1 executes firefox with firefox_args1 */
    launch_process(firefox_args1);
    /* child 2 executes firefox with firefox_args2 */
    launch_process(firefox_args2);
    /* child 3 executes gedit with gedit_args */
    launch_process(gedit_args);
    /* child 4 executes VLC with vlc_args */
    launch_process(vlc_args);

    /* Wait for all children: wait() returns -1 (errno ECHILD) when none is left */
    while (wait(NULL) > 0) {
        ;
    }

    return EXIT_SUCCESS;
}
src/test_thread.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

/**
 * @file test_thread.c
 *
 * @brief This program prints the process ID and the main thread ID of the
 * executing program.
 */

int main(void) {
    /* pthread_t is an opaque type: the cast is only for display purposes */
    printf("%ld / %lu\n", (long) getpid(), (unsigned long) pthread_self());
    return EXIT_SUCCESS;
}
src/update_w1.sh

View on GitHub

#!/bin/bash
#
# This Bash script sends SIGUSR1 to the process with ID $1 and SIGUSR2
# to the process with ID $2, repeating this action every minute 
# indefinitely.

if [ $# -ne 2 ]; then
    echo "Usage: $0 PID1 PID2   (PIDs shown by the two moving_window windows)" >&2
    exit 1
fi

# Stops as soon as one of the windows is closed (kill fails)
while true; do
    echo "Sending SIGUSR1 to $1"
    kill -s USR1 "$1" || exit 1
    echo "Sending SIGUSR2 to $2"
    kill -s USR2 "$2" || exit 1
    sleep 60
done
src/zombie.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "attendre.h"

/**
 * @file zombie.c
 *
 * @brief Montre un enfant zombie : l'enfant se termine, le parent ne le
 * récupère qu'après un appui sur Entrée (à observer avec ps).
 */

int main(void)
{
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if (pid == 0) {
        _exit(7);
    }
    printf("parent=%ld enfant=%ld\n", (long)getpid(), (long)pid);
    puts("Dans un autre terminal : ps -o pid,ppid,stat,comm -p PID_ENFANT");
    puts("Puis appuyer sur Entrée ici pour récupérer l'état de terminaison.");
    fflush(stdout);
    (void)getchar();
    int status;
    if (attendre(pid, &status) == -1) {
        perror("waitpid");
        return EXIT_FAILURE;
    }
    if (WIFEXITED(status)) {
        printf("état de terminaison récupéré : code %d\n", WEXITSTATUS(status));
        return EXIT_SUCCESS;
    }
    return EXIT_FAILURE;
}