Aller au contenu

Exemples sur les processus

Cette section contient des exemples liés à la gestion des processus en C. Ces exemples illustrent différents aspects de la création, de la gestion et de la communication des processus sur les systèmes de type Unix. Voici la liste des fichiers sources, avec leur description et un lien vers leur contenu.

Fichier Description Lien
process_01.c Illustre l'utilisation de l'appel système fork() pour créer un processus enfant process_01.c
process_02.c Montre comment la valeur d'une variable évolue indépendamment dans les processus parent et enfant process_02.c
process_03.c Illustre l'utilisation de fork() pour créer un processus enfant et utilise sleep() pour bloquer les processus parent et enfant pendant une durée donnée process_03.c
process_04a.c Clone un processus avec fork() et obtient un zombie process_04a.c
process_04b.c Illustre la création d'un processus orphelin en clonant un processus avec fork() et en faisant terminer le processus parent avant le processus enfant. process_04b.c
process_05.c Illustre l'utilisation de fork() pour créer un processus enfant, le processus parent attendant la fin du processus enfant puis vérifiant son état de terminaison process_05.c
process_06a.c Montre l'utilisation de fork() pour créer un processus enfant, qui exécute ensuite un nouveau programme (commande ls) avec execl(), tandis que le processus parent attend la fin de l'enfant process_06a.c
process_06b.c Montre l'utilisation de fork() pour créer un processus enfant, qui exécute ensuite un nouveau programme (gnuplot) avec execlp(), tandis que le processus parent attend la fin de l'enfant. process_06b.c
process_07.c L'enfant crée son propre groupe de processus avec setpgid(0, 0) (le parent fait le même appel, pour éviter une situation de compétition), puis le parent envoie SIGTERM à tout le groupe avec kill(-pgid, SIGTERM) (cours, chapitre "Signaux", diapositive "Groupes de processus") process_07.c
process_08.c Crée deux processus enfants avec fork(). Chaque enfant exécute l'application GTK ./bin/moving_window avec des paramètres différents au moyen de execv() (un chemin est fourni : pas de recherche dans PATH), tandis que le parent les attend tous les deux avec waitpid() (à lancer depuis 1_process/ ; nécessite GTK 3) process_08.c
process_09.c Crée quatre processus enfants avec fork(). Chaque enfant exécute une application (Firefox deux fois, Gedit, VLC) avec execvp(args[0], args) : le programme est recherché dans PATH ; le parent les attend tous process_09.c
test_thread.c Ce programme affiche l'identifiant du processus et l'identifiant du thread principal du programme en cours d'exécution test_thread.c
update_w1.sh Script Bash qui envoie SIGUSR1 et SIGUSR2 toutes les minutes aux deux processus moving_window dont les PID sont donnés (update_w1.sh PID1 PID2) ; s'arrête quand une fenêtre est fermée update_w1.sh
moving_window.c Fenêtre GTK qui prend une couleur prédéfinie à la réception de SIGUSR1 ou SIGUSR2 (le gestionnaire se contente de positionner un indicateur, lu par une minuterie GTK) ; utilisée par process_08.c et update_w1.sh ; nécessite GTK 3 moving_window.c
fork_memoire.c Après fork(), l'enfant modifie une copie d'une variable : les mémoires du parent et de l'enfant sont distinctes (cours, chapitre "Processus", exercice 1) fork_memoire.c
exec_variantes.c La famille exec côte à côte : execl, execlp, execv, execvp, execle, execve, puis trois erreurs classiques (argv[0] oublié, "ls -ld" comme nom de programme, execl sans chemin) ; le parent affiche chaque code de sortie, ou le signal qui a tué l'enfant (cours, chapitre "Processus", exercice 4 ; les diapositives utilisent ls -l) exec_variantes.c
lancer.c Lanceur minimal : fork() + execvp() + waitpid(), puis décode l'état de l'enfant avec WIFEXITED/WIFSIGNALED et affiche "code de sortie" ou "tué par le signal", comme sur la diapositive (cours, chapitre "Processus") lancer.c
zombie.c L'enfant se termine pendant que le parent attend l'appui sur une touche avant waitpid() : observer le zombie avec ps (cours, chapitre "Processus", exercice 3) zombie.c
attendre.h Utilitaire utilisé par exec_variantes.c, fork_memoire.c, lancer.c et zombie.c : waitpid() relancé en cas d'EINTR attendre.h

Code source

src/attendre.h

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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

Voir sur 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;
}