Aller au contenu

Exemples de synchronisation

Verrouillage de fichiers

Cette sous-section porte sur les mécanismes de verrouillage de fichiers en C à des fins de synchronisation. Voici le fichier source avec un lien vers son contenu.

Fichier Description Lien
lock_file.c Verrouille le fichier /tmp/test_lock avec lockf() : le lancer deux fois (./lock_file & ./lock_file) : le second processus réessaie toutes les secondes ("déjà verrouillé") jusqu'à ce que le premier déverrouille (cours, chapitre "Synchronisation") Voir

Sémaphores

Cette sous-section porte sur l'utilisation des sémaphores pour la synchronisation en C. Voici la liste des fichiers sources avec des liens vers leur contenu.

Fichier Description Lien
posix_prod_cons.c Producteur/consommateur entre deux processus enfants : tampon circulaire dans une mémoire partagée POSIX, trois sémaphores nommés empty, full, mutex (Ctrl-C pour arrêter) Voir
posix_semaphore.c P/V interactif sur un sémaphore POSIX nommé (le lancer dans deux terminaux ; x le détruit) Voir
unix_prod_cons.c Producteur/consommateur avec des sémaphores System V (Ctrl-C arrête les enfants ; le parent, qui l'ignore dès le départ, supprime les objets IPC) Voir
unix_semaphore.c P/V interactif sur un sémaphore System V ; usage : unix_semaphore key (le lancer dans deux terminaux) Voir
cnt_thread_semaphore.c Exemple fil rouge, correction 1 : compteur partagé protégé par un sémaphore anonyme (Linux uniquement : sem_init() n'est pas implémenté sur macOS) (cours, chapitre "Synchronisation") Voir
cnt_fork_named_semaphore.c Exemple fil rouge, correction 1, version fork : compteur en mémoire partagée protégé par un sémaphore nommé (très lent sur macOS avec la valeur par défaut de NB_ITERS) (cours, chapitre "Synchronisation") Voir
prod_cons_3_semaphores.c Producteur/consommateur entre deux threads avec un tampon circulaire et trois sémaphores vides, pleins, mutex (Linux uniquement : sem_init() n'est pas implémenté sur macOS) (cours, chapitre "Synchronisation") Voir

Exemples divers

Cette sous-section contient divers exemples liés aux mécanismes de synchronisation en C. Voici la liste des fichiers sources avec des liens vers leur contenu.

Fichier Description Lien
color_displayer.c Fenêtre Gtk qui lit la valeur RGB de sa couleur de fond dans une mémoire partagée Voir
color_displayer_without_synchro.c Fenêtre Gtk qui lit la valeur RGB de sa couleur de fond dans une mémoire partagée (version non synchronisée) Voir
color_writer.c Un processus qui modifie une valeur RGB dans une mémoire partagée, protégée par un sémaphore nommé ; Ctrl-C termine la boucle et supprime la mémoire partagée et le sémaphore (nécessite GTK 3 pour l'afficheur) Voir
color_writer_without_synchro.c Idem sans sémaphore (version non synchronisée) ; Ctrl-C supprime la mémoire partagée Voir
without_synchro.c Le parent et l'enfant décrémentent une valeur partagée sans synchronisation (situation de compétition volontaire) Voir
cnt_thread.c Exemple fil rouge : deux threads incrémentent un compteur partagé sans protection (mises à jour perdues) (cours, chapitre "Synchronisation") Voir
cnt_fork.c Exemple fil rouge : même échec de synchronisation avec deux processus enfants et une mémoire partagée POSIX (cours, chapitre "Synchronisation") Voir
cnt_thread_mutex.c Exemple fil rouge, correction 2 : compteur partagé protégé par un mutex (également dans le chapitre "Threads") (cours, chapitre "Synchronisation") Voir
cnt_thread_atomic.c Exemple fil rouge, correction 3 : compteur partagé de type C11 atomic_uint (cours, chapitre "Synchronisation") Voir
alarm_temperature.c Variable de condition : un thread d'alarme attend que la température mesurée sorte de la plage de 16 à 24 °C (cours, chapitre "Synchronisation") Voir
alarm_temperature_broadcast.c Variante avec deux threads d'alarme réveillés par pthread_cond_broadcast() (un prédicat par thread) (cours, chapitre "Synchronisation") Voir
prod_cons_conditions.c Producteur/consommateur entre deux threads avec un tampon circulaire, un mutex et deux variables de condition (cours, chapitre "Synchronisation") Voir

Code source

file_locking/src/lock_file.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>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

/**
 * @file lock_file.c
 *
 * This program demonstrates file locking by attempting to lock the file
 * /tmp/test_lock. If the file is already locked by another process, it waits
 * one second and retries until it can acquire the lock. Once locked, it holds
 * the lock for 3 seconds (simulated work) before unlocking and exiting.
 * Same program as the slides "lockf() - exemple" and "lockf() - exécution".
 *
 * \code{.bash}
 *   $ touch /tmp/test_lock
 *   $ ./lock_file & ./lock_file
 *   19357 : verrouillé
 *   19358 : déjà verrouillé
 *   19358 : déjà verrouillé
 *   19358 : déjà verrouillé
 *   19357 : déverrouillé
 *   19358 : verrouillé
 *   19358 : déverrouillé
 * \endcode
 */

/**
 * Handles a fatal error by displaying a message, then exits.
 */
void handle_fatal_error(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int open_lockfile(const char *name) {
    int fd = open(name, O_RDWR);  /* File must exist */
    if (fd == -1) {
        handle_fatal_error("Error opening file");
    }
    return fd;
}

int main(void) {
    int fd = open_lockfile("/tmp/test_lock");
    pid_t pid = getpid();

    while (1) {
        if (lockf(fd, F_TLOCK, 0) == -1) {
            if (errno == EACCES || errno == EAGAIN) {
                printf("%ld : déjà verrouillé\n", (long) pid);
                sleep(1);
            } else {
                handle_fatal_error("Error locking file");
            }
        } else {
            printf("%ld : verrouillé\n", (long) pid);
            sleep(3);   /* simulated work, lock held */

            if (lockf(fd, F_ULOCK, 0) == -1) {
                handle_fatal_error("Error unlocking file");
            }
            printf("%ld : déverrouillé\n", (long) pid);
            break;  /* Exit after unlocking the file */
        }
    }

    close(fd);
    return EXIT_SUCCESS;
}
semaphores/src/cnt_fork_named_semaphore.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>      /* printf(), perror() */
#include <stdlib.h>     /* exit() */
#include <fcntl.h>      /* O_* constants */
#include <unistd.h>     /* ftruncate(), fork(), close() */
#include <semaphore.h>  /* sem_open(), sem_wait(), sem_post(), sem_close() */
#include <sys/mman.h>   /* shm_open(), mmap(), munmap(), shm_unlink() */
#include <sys/wait.h>   /* wait() */

/**
 * @file cnt_fork_named_semaphore.c
 *
 * Running example, correction 1, fork version: two child processes
 * increment a counter in a POSIX shared memory segment, protected by a
 * named POSIX semaphore.
 * Lecture: chapter os-10 "Synchronisation", appendices ("Fil rouge -
 * correction 1, version fork" and "Sémaphore nommé - créer et observer").
 *
 * The named semaphore is opened before fork(): the children inherit it.
 * Under Linux, it is visible as /dev/shm/sem.cnt-sem until sem_unlink().
 * Failed version: ../../various/src/cnt_fork.c.
 * Works under Linux and macOS. Beware: under macOS, named semaphores are
 * very slow under contention (about 9 minutes measured for NB_ITERS =
 * 100000000): compile with e.g. -DNB_ITERS=1000000 for a quick test.
 * Link with \c -lrt -pthread under Linux.
 *
 * \code{.bash}
 *   $ ./cnt_fork_named_semaphore
 *   cnt=200000000
 * \endcode
 */

#ifndef NB_ITERS
#define NB_ITERS 100000000
#endif

/**
 * Handles a fatal error by displaying a message, then exits.
 */
void handle_fatal_error(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(void) {
    sem_unlink("/cnt-sem");        /* removes a semaphore left by a crash */
    sem_t *sem = sem_open("/cnt-sem", O_CREAT, 0600, 1);
    if (sem == SEM_FAILED) {
        handle_fatal_error("sem_open");
    }

    shm_unlink("/cnt");            /* removes a segment left by a crash */
    int fd = shm_open("/cnt", O_CREAT | O_RDWR, 0600);
    if (fd == -1) {
        handle_fatal_error("shm_open");
    }
    if (ftruncate(fd, sizeof(unsigned int)) == -1) {  /* set to zero */
        handle_fatal_error("ftruncate");
    }
    unsigned int *cnt = mmap(NULL, sizeof *cnt,
                             PROT_READ | PROT_WRITE,
                             MAP_SHARED, fd, 0);
    if (cnt == MAP_FAILED) {
        handle_fatal_error("mmap");
    }
    close(fd);

    for (int k = 0; k < 2; k++) {
        pid_t pid = fork();
        if (pid == -1) {
            handle_fatal_error("fork");
        }
        if (pid == 0) {            /* the child inherits sem */
            for (int i = 0; i < NB_ITERS; i++) {
                sem_wait(sem);
                (*cnt)++;
                sem_post(sem);
            }
            exit(EXIT_SUCCESS);
        }
    }
    wait(NULL);
    wait(NULL);
    printf("cnt=%u\n", *cnt);      /* 200000000 */

    sem_close(sem);
    sem_unlink("/cnt-sem");
    munmap(cnt, sizeof *cnt);
    shm_unlink("/cnt");

    return EXIT_SUCCESS;
}
semaphores/src/cnt_thread_semaphore.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 <pthread.h>    /* pthread_create(), pthread_join() */
#include <semaphore.h>  /* sem_init(), sem_wait(), sem_post(), sem_destroy() */
#include <stdio.h>      /* printf(), fprintf(), perror() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* strerror() */

/**
 * @file cnt_thread_semaphore.c
 *
 * Running example, correction 1: the shared counter protected by an
 * anonymous POSIX semaphore initialized to 1 (P / V around cnt++).
 * Lecture: chapter os-10 "Synchronisation" ("Fil rouge - correction 1 :
 * sémaphore").
 *
 * pshared = 0: the semaphore is shared by the threads of the process.
 * Failed version: ../../various/src/cnt_thread.c.
 *
 * LINUX ONLY: sem_init() is not implemented under macOS (ENOSYS); there,
 * use a named semaphore (see cnt_fork_named_semaphore.c) or a mutex.
 * Compile with \c -pthread.
 *
 * \code{.bash}
 *   $ ./cnt_thread_semaphore
 *   cnt=200000000
 * \endcode
 */

#ifndef NB_ITERS
#define NB_ITERS 100000000
#endif

unsigned int cnt = 0;
sem_t sem;                     /* a single declaration */

void *count(void *arg) {
    (void) arg;
    for (int i = 0; i < NB_ITERS; i++) {
        sem_wait(&sem);        /* P */
        cnt++;                 /* critical section */
        sem_post(&sem);        /* V */
    }
    return NULL;
}

int main(void) {
    pthread_t t1, t2;
    int err;

    if (sem_init(&sem, 0, 1) == -1) {   /* threads, value 1 */
        perror("sem_init (not supported on macOS)");
        exit(EXIT_FAILURE);
    }
    if ((err = pthread_create(&t1, NULL, count, NULL)) != 0 ||
        (err = pthread_create(&t2, NULL, count, NULL)) != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = pthread_join(t1, NULL)) != 0 ||
        (err = pthread_join(t2, NULL)) != 0) {
        fprintf(stderr, "pthread_join : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    sem_destroy(&sem);             /* cnt is 200000000 */
    printf("cnt=%u\n", cnt);

    return EXIT_SUCCESS;
}
semaphores/src/posix_prod_cons.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/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <semaphore.h>

/**
 * @file posix_prod_cons.c
 *
 * Producer-consumer program between two child processes, using a circular
 * buffer in a POSIX shared memory and three named POSIX semaphores:
 *   - empty (BUFFER_SIZE): free slots, blocks the producer when full;
 *   - full (0): occupied slots, blocks the consumer when empty;
 *   - mutex (1): protects the buffer.
 * The names are removed right after creation: the children inherit the
 * semaphores and the mapping, and nothing is left behind after Ctrl-C.
 */

#define BUFFER_SIZE  5
#define MEM_PATH     "/theshm"
#define SEM_EMPTY    "/theempty"
#define SEM_FULL     "/thefull"
#define SEM_MUTEX    "/themutex"

typedef sem_t semaphore_t;

void handle_fatal_error(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

void display_buffer(int *buffer) {
    printf("Buffer State: [ ");
    for (int i = 0; i < BUFFER_SIZE; i++) {
        printf("%d ", buffer[i]);
    }
    printf("]\n");
}

semaphore_t *setup_semaphore(const char *name, unsigned int value) {
    sem_unlink(name);  /* removes a semaphore left by a crash */
    semaphore_t *sem = sem_open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, value);
    if (sem == SEM_FAILED) {
        handle_fatal_error("sem_open failed");
    }
    sem_unlink(name);  /* still usable until sem_close() or exit */
    return sem;
}

int *setup_shared_memory(const char *name, size_t size) {
    int fd = shm_open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        handle_fatal_error("shm_open failed");
    }
    if (ftruncate(fd, size) == -1) {
        handle_fatal_error("ftruncate failed");
    }
    int *addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (addr == MAP_FAILED) {
        handle_fatal_error("mmap failed");
    }
    close(fd);  /* Close file descriptor as it's no longer needed */
    shm_unlink(name);  /* the mapping remains valid */
    return addr;
}

void produce(int *buffer, semaphore_t *empty, semaphore_t *full,
             semaphore_t *mutex) {
    int in_index = 0;
    srand((unsigned int)getpid());
    while (1) {
        sleep(1 + rand() % 5);
        int value = rand() % 100;
        sem_wait(empty);   /* a free slot */
        sem_wait(mutex);
        buffer[in_index] = value;
        printf("Produced: %d at %d\n", value, in_index);
        display_buffer(buffer);
        in_index = (in_index + 1) % BUFFER_SIZE;
        sem_post(mutex);
        sem_post(full);    /* one more occupied slot */
    }
}

void consume(int *buffer, semaphore_t *empty, semaphore_t *full,
             semaphore_t *mutex) {
    int out_index = 0;
    srand((unsigned int)getpid());
    while (1) {
        sem_wait(full);    /* an occupied slot */
        sem_wait(mutex);
        int value = buffer[out_index];
        printf("Consumed: %d from %d\n", value, out_index);
        display_buffer(buffer);
        out_index = (out_index + 1) % BUFFER_SIZE;
        sem_post(mutex);
        sem_post(empty);   /* one more free slot */
        sleep(2 + rand() % 5);
    }
}

int main(void) {
    semaphore_t *empty = setup_semaphore(SEM_EMPTY, BUFFER_SIZE);
    semaphore_t *full = setup_semaphore(SEM_FULL, 0);
    semaphore_t *mutex = setup_semaphore(SEM_MUTEX, 1);
    int *buffer = setup_shared_memory(MEM_PATH, BUFFER_SIZE * sizeof(int));

    pid_t pid = fork();
    if (pid == -1) {
        handle_fatal_error("fork failed");
    }
    if (pid == 0) {
        produce(buffer, empty, full, mutex);
        exit(EXIT_SUCCESS);
    }
    pid = fork();
    if (pid == -1) {
        handle_fatal_error("fork failed");
    }
    if (pid == 0) {
        consume(buffer, empty, full, mutex);
        exit(EXIT_SUCCESS);
    }

    /* Ctrl-C stops the three processes (nothing left: names removed) */
    wait(NULL);
    wait(NULL);

    return EXIT_SUCCESS;
}
semaphores/src/posix_semaphore.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 <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <semaphore.h>

/**
 * @file posix_semaphore.c
 * @brief A simple program used to implement a POSIX semaphore.
 *
 * This program is an interactive demonstration of POSIX semaphore usage. It
 * allows the user to perform semaphore operations like wait (P), signal (V),
 * destroy the semaphore (X), or quit the program (Q).
 *
 * Run it in two terminals: both processes open the same named semaphore
 * (initial value 1), so the second P() blocks until the other one does V().
 */

#define SEM_PATH "/thesemaphore"

typedef sem_t semaphore_t;

/**
 * Handles a fatal error. It displays a message, then exits.
 */
void handle_fatal_error(const char *message) {
    perror(message);
    exit(EXIT_FAILURE);
}

/**
 * Creates a POSIX semaphore and returns it.
 * @param name The name of the semaphore on the Unix system.
 * @return A pointer on the created POSIX semaphore.
 */
semaphore_t *create_and_open_semaphore(char *name) {
    semaphore_t *sem = NULL;

    /* No O_EXCL: a second process opens the existing semaphore */
    sem = sem_open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, 1);
    if (sem == SEM_FAILED) {
        handle_fatal_error("Error [sem_open()]");
    }
    return sem;
}

/**
 * Destroys the specified POSIX semaphore.
 * @param sem The identifier of the semaphore to destroy
 */
void destroy_semaphore(semaphore_t *sem, char *name) {
    int r = 0;

    r = sem_close(sem);
    if (r < 0) {
        handle_fatal_error("Error [sem_close()]");
    }
    r = sem_unlink(name);
    if (r < 0) {
        perror("Error [sem_unlink()]");
    }
}

/**
 * Performs a P() operation ("wait") on a semaphore.
 * @param sem Pointer on the semaphore.
 */
void P(semaphore_t *sem) {
    int r = 0;

    r = sem_wait(sem);
    if (r < 0) {
        handle_fatal_error("Error [P()]");
    }
}

/**
 * Performs a V() operation ("signal") on a semaphore.
 * @param sem Pointer on the semaphore.
 */
void V(semaphore_t *sem) {
    int r = 0;

    r = sem_post(sem);
    if (r < 0) {
        handle_fatal_error("Error [V()]");
    }
}

int main(void) {
    semaphore_t *sem = create_and_open_semaphore(SEM_PATH);
    char choice;

    while (1) {
        printf("p, v, x, q ? ");
        fflush(stdout);
        if (scanf(" %c", &choice) != 1) /* " %c" skips spaces and newlines */
            break;

        switch (toupper((unsigned char) choice)) {
            case 'P':
                P(sem);
                printf("P() -- Access granted to critical section\n");
                break;
            case 'V':
                V(sem);
                printf("V() -- Released critical section\n");
                break;
            case 'X':
                destroy_semaphore(sem, SEM_PATH);
                printf("Semaphore destroyed.\n");
                return EXIT_SUCCESS; /* Exit after destruction */
            case 'Q':
                return EXIT_SUCCESS; /* Clean exit */
            default:
                printf("Invalid choice. Use 'p', 'v', 'x', or 'q'.\n");
        }
    }

    return EXIT_SUCCESS;
}
semaphores/src/prod_cons_3_semaphores.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 <pthread.h>    /* pthread_create(), pthread_join() */
#include <semaphore.h>  /* sem_init(), sem_wait(), sem_post(), sem_destroy() */
#include <stdio.h>      /* printf(), fprintf(), perror() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* strerror() */

/**
 * @file prod_cons_3_semaphores.c
 *
 * Producer / consumer with a circular buffer of N slots and three anonymous
 * POSIX semaphores, between two threads.
 * Lecture: chapter os-10 "Synchronisation" ("Le tampon circulaire",
 * "Solution à trois sémaphores", "Producteur et consommateur").
 *
 *   - vides (N): free slots, blocks the producer when the buffer is full;
 *   - pleins (0): occupied slots, blocks the consumer when it is empty;
 *   - mutex (1): protects tampon, in and out.
 * Each thread takes a token "at home" and gives one back "at the other's".
 * The order of the P operations matters: counting semaphore first, then
 * mutex (the reverse leads to a deadlock when the buffer is full).
 *
 * In the lecture both threads loop forever; here the producer deposits
 * NB_ITEMS values and the consumer removes as many, so that the program
 * ends. See prod_cons_conditions.c (../../various/src) for the variant
 * with a mutex and condition variables.
 *
 * LINUX ONLY: sem_init() is not implemented under macOS (ENOSYS).
 * Compile with \c -pthread.
 *
 * \code{.bash}
 *   $ ./prod_cons_3_semaphores
 *   0
 *   1
 *   ...
 *   19
 * \endcode
 */

#define N 8
#define NB_ITEMS 20

int tampon[N];
int in = 0, out = 0;           /* circular indices */
sem_t vides, pleins, mutex;

void deposer(int x) {
    tampon[in] = x;
    in = (in + 1) % N;
}

int retirer(void) {
    int x = tampon[out];
    out = (out + 1) % N;
    return x;
}

void *producteur(void *a) {
    (void) a;
    for (int i = 0; i < NB_ITEMS; i++) {
        sem_wait(&vides);
        sem_wait(&mutex);
        deposer(i);
        sem_post(&mutex);
        sem_post(&pleins);
    }
    return NULL;
}

void *consommateur(void *a) {
    (void) a;
    for (int k = 0; k < NB_ITEMS; k++) {
        sem_wait(&pleins);
        sem_wait(&mutex);
        int x = retirer();
        sem_post(&mutex);
        sem_post(&vides);
        printf("%d\n", x);     /* outside the critical section */
    }
    return NULL;
}

int main(void) {
    pthread_t prod, cons;
    int err;

    if (sem_init(&vides, 0, N) == -1 ||      /* free slots */
        sem_init(&pleins, 0, 0) == -1 ||     /* occupied slots */
        sem_init(&mutex, 0, 1) == -1) {      /* access to the buffer */
        perror("sem_init (not supported on macOS)");
        exit(EXIT_FAILURE);
    }
    if ((err = pthread_create(&prod, NULL, producteur, NULL)) != 0 ||
        (err = pthread_create(&cons, NULL, consommateur, NULL)) != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = pthread_join(prod, NULL)) != 0 ||
        (err = pthread_join(cons, NULL)) != 0) {
        fprintf(stderr, "pthread_join : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }

    sem_destroy(&vides);
    sem_destroy(&pleins);
    sem_destroy(&mutex);

    return EXIT_SUCCESS;
}
semaphores/src/unix_prod_cons.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 <signal.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/**
 * @file unix_prod_cons.c
 *
 * @brief Producer-consumer program using a set of two System V IPC semaphores.
 *
 * This program demonstrates the producer-consumer problem solution using 
 * System V IPC semaphores for synchronization and shared memory for 
 * communication. It creates two processes, one for producing data and the
 * other for consuming it, with a shared buffer protected by a set of two 
 * semaphores. Stop it with Ctrl-C: the children are killed, and the parent,
 * which ignores SIGINT, collects them and removes the IPC objects.
 *
 * @author Alain Lebret (2011)
 * @author Janet Davis (2006)
 * @author Henry Walker (2004)
 * @version 1.0
 * @date 2011-12-01
 */

#define BUFFER_SIZE 10
#define BUFFER_SPACE 0
#define BUFFER_USED 1

typedef int semaphore_t;

/**
 * Handles a fatal error. It displays a message, then exits.
 */
void handle_fatal_error(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * Modifies the value of the specified System V semaphore.
 * @param sem The identifier of the set of semaphores
 * @param sem_num The index of the semaphore in the set
 * @param new_value The new value to associate to the semaphore
 */
void modify_semaphore_value(semaphore_t sem, int sem_num, int new_value) {
    struct sembuf sb[1];

    sb[0].sem_num = sem_num;
    sb[0].sem_op = new_value;
    sb[0].sem_flg = 0;

    if (semop(sem, sb, 1) != 0) {
        handle_fatal_error("Error [semop()]");
    }
}

/**
 * Performs a P() operation ("wait") on a semaphore.
 * @param sem Identifier of the semaphore.
 */
void P(semaphore_t sem, int sem_num) {
    modify_semaphore_value(sem, sem_num, -1);
}

/**
 * Performs a V() operation ("signal") on a semaphore.
 * @param sem Indentifier of the semaphore.
 */
void V(semaphore_t sem, int sem_num) {
    modify_semaphore_value(sem, sem_num, 1);
}

/**
 * Writes values to a shared buffer protected by semaphores.
 * @param buffer Buffer to read on.
 * @param id_semaphores Identifier of the set of two semaphores.
 */
void produce(int *buffer, int id_semaphores) {
    int in_index;
    int next_value;

    srand((unsigned int) getpid());
    in_index = 0;

    while (1) {  /* produce next_value */
        sleep((unsigned int) (5 + rand() % 5));
        next_value = rand() % 100;
        printf("producer: %d\n", next_value);

        P(id_semaphores, BUFFER_SPACE);

        buffer[in_index] = next_value;
        in_index = (in_index + 1) % BUFFER_SIZE;

        V(id_semaphores, BUFFER_USED);
    }

    /* Unreachable */
}

/**
 * Reads values from a shared buffer a shared buffer protected by semaphores.
 * @param buffer Buffer to read on.
 * @param id_semaphore Identifier of the set of two semaphores.
 */
void consume(int *buffer, int id_semaphores) {
    int out_index;
    int next_value;

    srand((unsigned int) getpid());
    out_index = 0;

    while (1) { /* consume next_value */

        P(id_semaphores, BUFFER_USED);

        next_value = buffer[out_index];
        out_index = (out_index + 1) % BUFFER_SIZE;

        V(id_semaphores, BUFFER_SPACE);

        /* consume next */
        printf("consumer: %d\n", next_value);
        sleep((unsigned int) (10 + rand() % 10));
    }

    /* Unreachable */
}

int main(void) {
    int *buffer;
    int id_semaphore;
    int id_memory;

    /* creation of the set of 2 IPC semaphores */
    id_semaphore = semget(IPC_PRIVATE, 2, 0600 | IPC_CREAT | IPC_EXCL);
    if (id_semaphore == -1) {
        handle_fatal_error("Error [semget()]");
    }

    /* initialization of the two semaphores */
    /* POSIX passes the 4th argument of semctl(SETVAL) as a union semun
       (field val), which the program must define itself on Linux; passing
       an int works on the usual ABIs (Linux, macOS), as here. */
    if (semctl(id_semaphore, BUFFER_USED, SETVAL, 0) == -1
        || semctl(id_semaphore, BUFFER_SPACE, SETVAL, BUFFER_SIZE) == -1) {
        semctl(id_semaphore, 0, IPC_RMID);
        handle_fatal_error("Error [semctl(SETVAL)]");
    }

    /* creation and attachment of a shared memory */
    id_memory = shmget(IPC_PRIVATE, BUFFER_SIZE * sizeof(int),
                       0600 | IPC_CREAT | IPC_EXCL);
    if (id_memory == -1) {
        semctl(id_semaphore, 0, IPC_RMID);
        handle_fatal_error("Error [shmget()]");
    }
    buffer = shmat(id_memory, NULL, 0);
    if (buffer == (void *) -1) {
        semctl(id_semaphore, 0, IPC_RMID);
        shmctl(id_memory, IPC_RMID, NULL);
        handle_fatal_error("Error [shmat()]");
    }

    /* Ctrl-C kills the children; the parent ignores it to clean up. SIGINT is
       ignored before fork(): an early Ctrl-C cannot leave the IPC objects. */
    struct sigaction sa;
    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        handle_fatal_error("Error [sigaction()]");
    }

    for (int k = 0; k < 2; k++) {
        pid_t pid = fork();
        if (pid == -1) {
            handle_fatal_error("Error [fork()]");
        }
        if (pid == 0) {
            sa.sa_handler = SIG_DFL; /* children: Ctrl-C stops them again */
            sigaction(SIGINT, &sa, NULL);
            if (k == 0) {
                produce(buffer, id_semaphore);
            } else {
                consume(buffer, id_semaphore);
            }
            exit(EXIT_SUCCESS);     /* unreachable */
        }
    }

    while (wait(NULL) > 0) {
        ;
    }

    /* remove IPC objects */
    shmdt(buffer);
    semctl(id_semaphore, 0, IPC_RMID);
    shmctl(id_memory, IPC_RMID, NULL);

    return EXIT_SUCCESS;
}
semaphores/src/unix_semaphore.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 <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

/**
 * @file unix_semaphore.c
 *
 * Example using a System V semaphore.
 *
 * This program is an interactive demonstration of System V semaphore usage. 
 * It allows the user to perform semaphore operations like wait (P), signal
 * (V), destroy the semaphore (X), or quit the program (Q).
 * Run it in two terminals with the same key: the first one creates the
 * semaphore with the value 0, the second one opens it without resetting it.
 *
 * @author Alain Lebret
 * @author Michel Billaud <michel.billaud@labri.fr>
 * @version 1.1
 * @date 2011-12-01
 */

#define TRUE 1
#define FALSE 0

typedef int semaphore_t;

/**
 * Handles a fatal error. It displays a message, then exits.
 */
void handle_fatal_error(const char *message) {
    perror(message);
    exit(EXIT_FAILURE);
}

/**
 * Creates (or opens) a System V semaphore and returns its identifier.
 * @return The identifier of the System V semaphore.
 */
semaphore_t create_semaphore(key_t key) {
    semaphore_t sem;
    int r;

    sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 0600);
    if (sem < 0) {                      /* already created: just open it */
        sem = semget(key, 1, 0600);
        if (sem < 0) {
            handle_fatal_error("Error [semget()]");
        }
        return sem;
    }
    /* POSIX passes the 4th argument of semctl(SETVAL) as a union semun
       (field val), which the program must define itself on Linux; passing
       an int works on the usual ABIs (Linux, macOS), as here. */
    r = semctl(sem, 0, SETVAL, 0);      /* initial value = 0 */
    if (r < 0) {
        handle_fatal_error("Error [semctl()]");
    }

    return sem;
}

/**
 * Destroys the specified System V semaphore.
 * @param sem The identifier of the semaphore to destroy
 */
void destroy_semaphore(semaphore_t sem) {
    if (semctl(sem, 0, IPC_RMID, 0) != 0)
        handle_fatal_error("Error [semctl()]");
}

/**
 * Modifies the value of the specified System V semaphore.
 * @param sem The identifier of the semaphore
 * @param new_value The new value to associate to the semaphore
 */
void modify_semaphore_value(semaphore_t sem, int new_value) {
    struct sembuf sb[1];

    sb[0].sem_num = 0;
    sb[0].sem_op = new_value;
    sb[0].sem_flg = 0;

    if (semop(sem, sb, 1) != 0)
        handle_fatal_error("Error [semop()]");
}

/**
 * Performs a P() operation ("wait") on a semaphore.
 * @param sem Identifier of the semaphore.
 */
void P(semaphore_t sem) {
    modify_semaphore_value(sem, -1);
}

/**
 * Performs a V() operation ("signal") on a semaphore.
 * @param sem Indentifier of the semaphore.
 */
void V(semaphore_t sem) {
    modify_semaphore_value(sem, 1);
}

int main(int argc, char *argv[]) {
    semaphore_t sem;
    key_t key;
    char choice;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s key\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    key = atoi(argv[1]);
    sem = create_semaphore(key);

    while (1) {
        printf("p, v, x, q ? ");
        fflush(stdout);
        if (scanf(" %c", &choice) != 1) /* " %c" skips spaces and newlines */
            break;

        switch (toupper((unsigned char) choice)) {
            case 'P':
                P(sem);
                printf("P() -- Access granted to critical section\n");
                break;
            case 'V':
                V(sem);
                printf("V() -- Released critical section\n");
                break;
            case 'X':
                destroy_semaphore(sem);
                printf("Semaphore destroyed.\n");
                return EXIT_SUCCESS; /* Exit after destruction */
            case 'Q':
                return EXIT_SUCCESS; /* Clean exit */
            default:
                printf("Invalid choice. Use 'p', 'v', 'x', or 'q'.\n");
        }
    }


    return EXIT_SUCCESS;
}
various/src/alarm_temperature.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 <pthread.h>    /* pthread_*, pthread_mutex_*, pthread_cond_* */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* srand(), rand(), exit() */
#include <string.h>     /* strerror() */
#include <time.h>       /* time() */
#include <unistd.h>     /* sleep() */

/**
 * @file alarm_temperature.c
 *
 * Condition variable example: a thread measures a temperature every
 * second; another thread sleeps until the temperature leaves the range
 * 16 to 24 °C, then displays an alarm.
 * Lecture: chapter os-10 "Synchronisation" ("Exemple - alarme et
 * température").
 *
 * Key points:
 *   - the predicate (alarme) is protected by the mutex m;
 *   - pthread_cond_wait() is always called in a while (!predicate) loop
 *     (spurious wakeups);
 *   - the predicate is modified under the mutex, then signalled;
 *   - printf() is called after unlocking: short critical section;
 *   - main() ends with pthread_exit(): the threads go on (Ctrl-C to stop).
 * See alarm_temperature_broadcast.c for several alarm threads.
 *
 * \code{.bash}
 *   $ ./alarm_temperature
 *   Température : 21
 *   Température : 20
 *   ...
 *   Température : 25
 *   ALARME
 * \endcode
 */

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  c = PTHREAD_COND_INITIALIZER;
int alarme = 0;                /* the predicate */

void *send_alarm(void *unused);
void *get_temperature(void *unused);

int main(void) {
    pthread_t t1, t2;
    int err;

    srand(time(NULL));
    if ((err = pthread_create(&t1, NULL, get_temperature, NULL)) != 0 ||
        (err = pthread_create(&t2, NULL, send_alarm, NULL)) != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    pthread_exit(NULL);        /* the threads go on */
}

void *send_alarm(void *unused) {
    (void) unused;
    while (1) {
        pthread_mutex_lock(&m);
        while (!alarme) {
            pthread_cond_wait(&c, &m);
        }
        alarme = 0;            /* event consumed */
        pthread_mutex_unlock(&m);
        printf("ALARME\n");
    }
    return NULL;
}

void *get_temperature(void *unused) {
    (void) unused;
    int t = 20;
    while (1) {
        t += rand() % 3 - 1;   /* -1, 0 or +1 */
        printf("Température : %d\n", t);
        if (t < 16 || t > 24) {
            pthread_mutex_lock(&m);
            alarme = 1;        /* predicate true */
            pthread_cond_signal(&c);
            pthread_mutex_unlock(&m);
        }
        sleep(1);
    }
    return NULL;
}
various/src/alarm_temperature_broadcast.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 <pthread.h>    /* pthread_*, pthread_mutex_*, pthread_cond_* */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* srand(), rand(), exit() */
#include <string.h>     /* strerror() */
#include <time.h>       /* time() */
#include <unistd.h>     /* sleep() */

/**
 * @file alarm_temperature_broadcast.c
 *
 * Variant of alarm_temperature.c with two alarm threads, both woken up by
 * pthread_cond_broadcast().
 * Lecture: chapter os-10 "Synchronisation" ("Plusieurs threads en
 * attente : broadcast" and, in the appendices, "Broadcast - un prédicat
 * par thread").
 *
 * With the predicate alarme = 0 of alarm_temperature.c, the first thread
 * woken up would consume the event and the other would go back to sleep.
 * Here the shared predicate is a counter of alarms (nb_alarmes), and each
 * thread remembers in a private variable (vues) the last value it saw:
 * both threads are informed of each alarm.
 * Ctrl-C to stop.
 *
 * \code{.bash}
 *   $ ./alarm_temperature_broadcast
 *   Température : 21
 *   ...
 *   Température : 15
 *   ALARME (thread 2)
 *   ALARME (thread 3)
 * \endcode
 */

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  c = PTHREAD_COND_INITIALIZER;
int nb_alarmes = 0;            /* shared */

void *send_alarm(void *arg) {
    long num = (long) arg;
    int vues = 0;              /* private */
    while (1) {
        pthread_mutex_lock(&m);
        while (nb_alarmes == vues) {
            pthread_cond_wait(&c, &m);
        }
        vues = nb_alarmes;
        pthread_mutex_unlock(&m);
        printf("ALARME (thread %ld)\n", num);
    }
    return NULL;
}

void *get_temperature(void *unused) {
    (void) unused;
    int t = 20;
    while (1) {
        t += rand() % 3 - 1;   /* -1, 0 or +1 */
        printf("Température : %d\n", t);
        if (t < 16 || t > 24) {
            pthread_mutex_lock(&m);
            nb_alarmes++;      /* new event */
            pthread_cond_broadcast(&c);
            pthread_mutex_unlock(&m);
        }
        sleep(1);
    }
    return NULL;
}

int main(void) {
    pthread_t t1, t2, t3;
    int err;

    srand(time(NULL));
    if ((err = pthread_create(&t1, NULL, get_temperature, NULL)) != 0 ||
        (err = pthread_create(&t2, NULL, send_alarm, (void *) 2L)) != 0 ||
        (err = pthread_create(&t3, NULL, send_alarm, (void *) 3L)) != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    pthread_exit(NULL);        /* the threads go on */
}
various/src/cnt_fork.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>      /* printf(), perror() */
#include <stdlib.h>     /* exit() */
#include <fcntl.h>      /* O_* constants */
#include <unistd.h>     /* ftruncate(), fork(), close() */
#include <sys/mman.h>   /* shm_open(), mmap(), munmap(), shm_unlink() */
#include <sys/wait.h>   /* wait() */

/**
 * @file cnt_fork.c
 *
 * Running example, failed synchronization (fork version): two child
 * processes increment a counter placed in a POSIX shared memory segment,
 * NB_ITERS times each, without protection.
 * Lecture: chapter os-10 "Synchronisation" ("Synchronisation ratée -
 * version fork").
 *
 * Same defect as with threads (cnt_thread.c): cnt should be 200 000 000,
 * but the result is wrong and changes at each execution.
 * The counter is accessed through a volatile pointer so that the optimizer
 * does not merge the loop. Correction with a named semaphore:
 * ../semaphores/src/cnt_fork_named_semaphore.c.
 * Link with \c -lrt under Linux.
 *
 * \code{.bash}
 *   $ ./cnt_fork
 *   cnt=65486848
 *   $ ./cnt_fork
 *   cnt=113868800
 * \endcode
 */

#ifndef NB_ITERS
#define NB_ITERS 100000000
#endif

/**
 * Handles a fatal error by displaying a message, then exits.
 */
void handle_fatal_error(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(void) {
    shm_unlink("/cnt");            /* removes a segment left by a crash */
    int fd = shm_open("/cnt", O_CREAT | O_RDWR, 0600);
    if (fd == -1) {
        handle_fatal_error("shm_open");
    }
    if (ftruncate(fd, sizeof(unsigned int)) == -1) {  /* set to zero */
        handle_fatal_error("ftruncate");
    }
    volatile unsigned int *cnt = mmap(NULL, sizeof *cnt,
                                      PROT_READ | PROT_WRITE,
                                      MAP_SHARED, fd, 0);
    if (cnt == MAP_FAILED) {
        handle_fatal_error("mmap");
    }
    close(fd);

    for (int k = 0; k < 2; k++) {
        pid_t pid = fork();
        if (pid == -1) {
            handle_fatal_error("fork");
        }
        if (pid == 0) {                   /* child */
            for (int i = 0; i < NB_ITERS; i++) {
                (*cnt)++;                 /* shared */
            }
            exit(EXIT_SUCCESS);
        }
    }
    wait(NULL);
    wait(NULL);                           /* two children */
    printf("cnt=%u\n", *cnt);

    munmap((void *) cnt, sizeof *cnt);
    shm_unlink("/cnt");

    return EXIT_SUCCESS;
}
various/src/cnt_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 <pthread.h>    /* pthread_create(), pthread_join() */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* strerror() */

/**
 * @file cnt_thread.c
 *
 * Running example, failed synchronization (thread version): two threads
 * increment a shared counter NB_ITERS times each, without protection.
 * Lecture: chapter os-10 "Synchronisation" ("Synchronisation ratée -
 * version thread"), also shown in chapter os-08 "Threads".
 *
 * cnt should be 200 000 000, but the result is wrong and changes from one
 * execution to the next: cnt++ is three instructions (Load, Add, Store),
 * so updates get lost when the two threads interleave.
 *
 * The counter is declared volatile, as suggested in the lecture: otherwise
 * the optimizer (-O2) may merge the loop into a single cnt += NB_ITERS.
 * Corrections: cnt_thread_mutex.c, cnt_thread_atomic.c and
 * ../semaphores/src/cnt_thread_semaphore.c.
 *
 * \code{.bash}
 *   $ gcc -O0 -pthread -o cnt_thread cnt_thread.c
 *   $ ./cnt_thread
 *   cnt=94832671
 *   $ ./cnt_thread
 *   cnt=101488317
 * \endcode
 */

#ifndef NB_ITERS
#define NB_ITERS 100000000
#endif

volatile unsigned int cnt = 0;       /* shared */

void *count(void *arg) {
    (void) arg;
    for (int i = 0; i < NB_ITERS; i++) {
        cnt++;
    }
    return NULL;
}

int main(void) {
    pthread_t t1, t2;
    int err;

    if ((err = pthread_create(&t1, NULL, count, NULL)) != 0 ||
        (err = pthread_create(&t2, NULL, count, NULL)) != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = pthread_join(t1, NULL)) != 0 ||
        (err = pthread_join(t2, NULL)) != 0) {
        fprintf(stderr, "pthread_join : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    printf("cnt=%u\n", cnt);

    return EXIT_SUCCESS;
}
various/src/cnt_thread_atomic.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 <pthread.h>    /* pthread_create(), pthread_join() */
#include <stdatomic.h>  /* atomic_uint, atomic_fetch_add() */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* strerror() */

/**
 * @file cnt_thread_atomic.c
 *
 * Running example, correction 3: the shared counter is a C11 atomic
 * variable.
 * Lecture: chapter os-10 "Synchronisation" ("Fil rouge - correction 3 :
 * atomique").
 *
 * atomic_fetch_add() is a single indivisible instruction (x86: lock add):
 * neither lock nor waiting queue. On an atomic_uint, cnt++ is atomic too.
 * It only suits a simple operation on one variable.
 * Failed version: cnt_thread.c.
 *
 * \code{.bash}
 *   $ ./cnt_thread_atomic
 *   cnt=200000000
 * \endcode
 */

#ifndef NB_ITERS
#define NB_ITERS 100000000
#endif

atomic_uint cnt = 0;

void *count(void *arg) {
    (void) arg;
    for (int i = 0; i < NB_ITERS; i++) {
        atomic_fetch_add(&cnt, 1);
    }
    return NULL;
}

int main(void) {
    pthread_t t1, t2;
    int err;

    if ((err = pthread_create(&t1, NULL, count, NULL)) != 0 ||
        (err = pthread_create(&t2, NULL, count, NULL)) != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = pthread_join(t1, NULL)) != 0 ||
        (err = pthread_join(t2, NULL)) != 0) {
        fprintf(stderr, "pthread_join : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    printf("cnt=%u\n", atomic_load(&cnt));

    return EXIT_SUCCESS;
}
various/src/cnt_thread_mutex.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 <pthread.h>    /* pthread_create(), pthread_join(), pthread_mutex_* */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* strerror() */

/**
 * @file cnt_thread_mutex.c
 *
 * Running example, correction 2: the shared counter protected by a mutex.
 * Lecture: chapter os-10 "Synchronisation" ("Fil rouge - correction 2 :
 * mutex"), also shown in chapter os-08 "Threads" ("Vers le chapitre
 * Synchronisation").
 *
 * The sequence Load, Add, Store of cnt++ becomes indivisible: the result is
 * 200 000 000, but the program is slower since the threads wait for each
 * other. The thread that locks is the one that unlocks: the mutex is the
 * natural tool. main() is unchanged: no dynamic initialization is needed.
 * Failed version: cnt_thread.c.
 *
 * \code{.bash}
 *   $ ./cnt_thread_mutex
 *   cnt=200000000
 * \endcode
 */

#ifndef NB_ITERS
#define NB_ITERS 100000000
#endif

unsigned int cnt = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

void *count(void *arg) {
    (void) arg;
    for (int i = 0; i < NB_ITERS; i++) {
        pthread_mutex_lock(&m);
        cnt++;                 /* critical section */
        pthread_mutex_unlock(&m);
    }
    return NULL;
}

int main(void) {
    pthread_t t1, t2;
    int err;

    if ((err = pthread_create(&t1, NULL, count, NULL)) != 0 ||
        (err = pthread_create(&t2, NULL, count, NULL)) != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = pthread_join(t1, NULL)) != 0 ||
        (err = pthread_join(t2, NULL)) != 0) {
        fprintf(stderr, "pthread_join : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    printf("cnt=%u\n", cnt);

    return EXIT_SUCCESS;
}
various/src/color_displayer.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 <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <gtk/gtk.h>
#include <semaphore.h>

/**
 * @file color_displayer.c
 *
 * This GTK application is designed to display colors that are updated 
 * periodically. The color data is intended to be read from a shared 
 * memory segment and displayed in a GTK window. The string is copied
 * under the protection of the named semaphore created by color_writer.c.
 */

#define SHM_NAME "/my_shared_memory"
#define SHM_SIZE 1024
#define SEM_NAME "/my_semaphore"

typedef struct {
    GtkWidget *label;          /* Displays the "R,G,B" string */
    GtkCssProvider *css;       /* Background color of the window */
    const char *shared_memory; /* Color data written by color_writer */
    sem_t *semaphore;
} shared_data;

/**
 * Handles a fatal error. It displays a message, then exits.
 */
void handle_fatal_error(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * Updates colors from the shared memory. Called every second by the GTK
 * main loop (GSourceFunc: a single gpointer argument, returns a gboolean).
 */
gboolean update_colors(gpointer user_data) {
    shared_data *data = user_data;
    char color_data[32];
    char css[80];
    int red;
    int green;
    int blue;

    sem_wait(data->semaphore);  /* Enter the critical section */
    snprintf(color_data, sizeof(color_data), "%.31s", data->shared_memory);
    sem_post(data->semaphore);  /* Leave the critical section */

    /* Split the local copy into R, G, and B components */
    if (sscanf(color_data, "%d,%d,%d", &red, &green, &blue) == 3) {
        snprintf(css, sizeof(css), "* { background-color: rgb(%d,%d,%d); }",
                 red, green, blue);
        gtk_css_provider_load_from_data(data->css, css, -1, NULL);
        gtk_label_set_text(GTK_LABEL(data->label), color_data);
    }

    return G_SOURCE_CONTINUE;   /* Keep the timer */
}

int main(int argc, char *argv[]) {
    int shm_fd;
    char *shared_memory;
    shared_data data;
    GtkWidget *window;
    GtkWidget *colorDisplay;
    sem_t *sem;

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

    /* Create a GTK window whose background color is set by a CSS provider */
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(window), 300, 200);
    g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), NULL);
    data.css = gtk_css_provider_new();
    gtk_style_context_add_provider(gtk_widget_get_style_context(window),
                                   GTK_STYLE_PROVIDER(data.css),
                                   GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    /* Create other GTK widgets to display colors */
    colorDisplay = gtk_label_new(NULL);
    gtk_container_add(GTK_CONTAINER(window), colorDisplay);

    /* Open the shared memory */
    shm_fd = shm_open(SHM_NAME, O_RDONLY, S_IRUSR | S_IWUSR);
    if (shm_fd == -1) {
        handle_fatal_error("Error [shm_open()]");
    }

    /* Map the shared memory */
    shared_memory = (char *) mmap(NULL, SHM_SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
    if (shared_memory == MAP_FAILED) {
        handle_fatal_error("Error [mmap()]");
    }

    /* Open the semaphore */
    sem = sem_open(SEM_NAME, 0);
    if (sem == SEM_FAILED) {
        handle_fatal_error("Error [sem_open()]");
    }

    data.label = colorDisplay;
    data.shared_memory = shared_memory;
    data.semaphore = sem;

    /* Create a timer to update colors periodically */
    g_timeout_add(1000, update_colors, &data);

    /* Show the window and start the GTK main loop */
    gtk_widget_show_all(window);
    gtk_main();

    /* Clean up */
    munmap(shared_memory, SHM_SIZE);
    close(shm_fd);
    sem_close(sem);
    g_object_unref(data.css);

    return EXIT_SUCCESS;
}
various/src/color_displayer_without_synchro.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 <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <gtk/gtk.h>

/**
 * @file color_displayer_without_synchro.c
 *
 * This GTK application is designed to display colors that are updated 
 * periodically. The color data is intended to be read from a shared 
 * memory segment and displayed in a GTK window.
 *
 * WARNING: synchronization is deliberately missing (see
 * color_writer_without_synchro.c). Compare with color_displayer.c.
 */

#define SHM_NAME "/color_memory"
#define SHM_SIZE 1024

typedef struct {
    GtkCssProvider *css;       /* Background color of the window */
    const char *shared_memory; /* Color data written by the writer */
} shared_data;

/**
 * Handles a fatal error. It displays a message, then exits.
 */
void handle_fatal_error(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * Updates colors from the shared memory. Called every second by the GTK
 * main loop (GSourceFunc: a single gpointer argument, returns a gboolean).
 * No synchronization: the string may be read while it is being written.
 */
gboolean update_colors(gpointer user_data) {
    shared_data *data = user_data;
    char css[80];
    int red;
    int green;
    int blue;

    /* The shared memory contains color data in "R,G,B" format */
    if (sscanf(data->shared_memory, "%d,%d,%d", &red, &green, &blue) == 3) {
        snprintf(css, sizeof(css), "* { background-color: rgb(%d,%d,%d); }",
                 red, green, blue);
        gtk_css_provider_load_from_data(data->css, css, -1, NULL);
    }

    return G_SOURCE_CONTINUE;   /* Keep the timer */
}

int main(int argc, char *argv[]) {
    int shm_fd;
    char *shared_memory;
    shared_data data;
    GtkWidget *window;
    GtkWidget *colorDisplay;

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

    /* Create a GTK window whose background color is set by a CSS provider */
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(window), 300, 200);
    g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), NULL);
    data.css = gtk_css_provider_new();
    gtk_style_context_add_provider(gtk_widget_get_style_context(window),
                                   GTK_STYLE_PROVIDER(data.css),
                                   GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    /* Create other GTK widgets to display colors */
    colorDisplay = gtk_label_new(NULL);
    gtk_container_add(GTK_CONTAINER(window), colorDisplay);

    /* Open the shared memory */
    shm_fd = shm_open(SHM_NAME, O_RDONLY, S_IRUSR | S_IWUSR);
    if (shm_fd == -1) {
        handle_fatal_error("Error [shm_open()]");
    }

    /* Map the shared memory */
    shared_memory = (char *) mmap(NULL, SHM_SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
    if (shared_memory == MAP_FAILED) {
        handle_fatal_error("Error [mmap()]");
    }
    data.shared_memory = shared_memory;

    /* Create a timer to update colors periodically */
    g_timeout_add(1000, update_colors, &data);

    /* Show the window and start the GTK main loop */
    gtk_widget_show_all(window);
    gtk_main();

    /* Clean up */
    munmap(shared_memory, SHM_SIZE);
    close(shm_fd);
    g_object_unref(data.css);

    return EXIT_SUCCESS;
}
various/src/color_writer.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() */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <time.h>
#include <signal.h>

/**
 * @file color_writer.c
 *
 * This program continuously generates random RGB color values and writes them
 * as a formatted string to a shared memory segment, using a semaphore for 
 * synchronization. It's designed to run indefinitely, updating the shared 
 * memory with new color data every second.
 */

#define SHM_NAME "/my_shared_memory"
#define SHM_SIZE 1024
#define SEM_NAME "/my_semaphore"

/* Set by the SIGINT handler (Ctrl-C): the main loop stops and cleans up */
static volatile sig_atomic_t keep_running = 1;

void handle_sigint(int signum) {
    (void) signum;
    keep_running = 0;
}

/* Generate a random integer between min and max */
int random_int(int min, int max) {
    return min + rand() % (max - min + 1);
}

int main(void) {
    int shm_fd;
    int red;
    int green;
    int blue;
    void *shm_ptr;
    char *color_data;
    sem_t *semaphore;

    /* Create or open the shared memory segment */
    shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    if (shm_fd == -1) {
        perror("shm_open");
        exit(1);
    }

    /* Set the size of the shared memory segment */
    if (ftruncate(shm_fd, SHM_SIZE) == -1) {
        perror("ftruncate");
        exit(1);
    }

    /* Map the shared memory into the address space */
    shm_ptr = mmap(0, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (shm_ptr == MAP_FAILED) {
        perror("mmap");
        exit(1);
    }

    /* Pointer to the color data in shared memory */
    color_data = (char *) shm_ptr;

    /* Create or open the semaphore */
    semaphore = sem_open(SEM_NAME, O_CREAT, 0600, 1); /* Initial value is 1 */
    if (semaphore == SEM_FAILED) {
        perror("sem_open");
        exit(1);
    }

    /* Ctrl-C ends the loop instead of killing the program, so that the
       shared memory and the semaphore are removed below */
    struct sigaction action;
    memset(&action, 0, sizeof(action));
    action.sa_handler = handle_sigint;
    sigemptyset(&action.sa_mask);
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    /* Seed the random number generator with the current time */
    srand(time(NULL));

    while (keep_running) {
        /* Generate random RGB color values */
        red = random_int(0, 255);
        green = random_int(0, 255);
        blue = random_int(0, 255);

        /* Format the color data as a string (e.g., "255,0,0" for red) */
        sem_wait(semaphore);   /* Enter the critical section */
        snprintf(color_data, SHM_SIZE, "%d,%d,%d", red, green, blue);
        sem_post(semaphore);   /* Leave the critical section */

        /* Print the generated color for debugging */
        printf("Generated Color: %d,%d,%d\n", red, green, blue);

        /* Sleep or do some work */
        sleep(1); /* Sleep for 1 second */
    }

    /* Unmap and close the shared memory segment when done */
    munmap(shm_ptr, SHM_SIZE);
    close(shm_fd);
    shm_unlink(SHM_NAME);

    /* Close and unlink the semaphore when done */
    sem_close(semaphore);
    sem_unlink(SEM_NAME);

    return EXIT_SUCCESS;
}
various/src/color_writer_without_synchro.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() */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <time.h>
#include <signal.h>

/**
 * @file color_writer_without_synchro.c
 *
 * This program continuously generates random RGB color values and writes
 * them as a formatted string to a shared memory segment. It's designed
 * to run indefinitely, updating the shared memory with new color data 
 * every second.
 *
 * WARNING: synchronization is deliberately missing (no semaphore), so the
 * displayer may read a string that is being written. Compare with
 * color_writer.c.
 */

#define SHM_NAME "/color_memory"
#define SHM_SIZE 1024

/* Set by the SIGINT handler (Ctrl-C): the main loop stops and cleans up */
static volatile sig_atomic_t keep_running = 1;

void handle_sigint(int signum) {
    (void) signum;
    keep_running = 0;
}

/* Function to generate a random integer between min and max */
int random_int(int min, int max) {
    return min + rand() % (max - min + 1);
}

int main(void) {
    int shm_fd;
    void *shm_ptr;
    char *color_data;

    /* Create or open the shared memory segment */
    shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    if (shm_fd == -1) {
        perror("shm_open");
        exit(1);
    }

    /* Set the size of the shared memory segment */
    if (ftruncate(shm_fd, SHM_SIZE) == -1) {
        perror("ftruncate");
        exit(1);
    }

    /* Map the shared memory into the address space */
    shm_ptr = mmap(0, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (shm_ptr == MAP_FAILED) {
        perror("mmap");
        exit(1);
    }

    /* Pointer to the color data in shared memory */
    color_data = (char *) shm_ptr;


    /* Ctrl-C ends the loop instead of killing the program, so that the
       shared memory is removed below */
    struct sigaction action;
    memset(&action, 0, sizeof(action));
    action.sa_handler = handle_sigint;
    sigemptyset(&action.sa_mask);
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    /* Seed the random number generator with the current time */
    srand(time(NULL));

    while (keep_running) {
        /* Generate random RGB color values */
        int red = random_int(0, 255);
        int green = random_int(0, 255);
        int blue = random_int(0, 255);

        /* Format the color data as a string (e.g., "255,0,0" for red) */
        snprintf(color_data, SHM_SIZE, "%d,%d,%d", red, green, blue);

        /* Print the generated color for debugging */
        printf("Generated Color: %d,%d,%d\n", red, green, blue);

        /* Sleep or do some work */
        sleep(1); /* Sleep for 1 second */
    }

    /* Unmap, close and destroy the shared memory segment when done */
    munmap(shm_ptr, SHM_SIZE);
    close(shm_fd);
    shm_unlink(SHM_NAME);

    return EXIT_SUCCESS;
}
various/src/prod_cons_conditions.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 <pthread.h>    /* pthread_*, pthread_mutex_*, pthread_cond_* */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* strerror() */

/**
 * @file prod_cons_conditions.c
 *
 * Producer / consumer with a circular buffer of N slots, a mutex and two
 * condition variables (non_plein, non_vide), between two threads.
 * Lecture: chapter os-10 "Synchronisation" ("Variante : mutex et
 * conditions").
 *
 * The producer waits while the buffer is full (nb == N), the consumer
 * while it is empty (nb == 0); each one signals the other after its
 * operation. Works under macOS, unlike the version with anonymous
 * semaphores (../../semaphores/src/prod_cons_3_semaphores.c).
 *
 * In the lecture both threads loop forever; here the producer deposits
 * NB_ITEMS values and the consumer removes as many, so that the program
 * ends.
 *
 * \code{.bash}
 *   $ ./prod_cons_conditions
 *   0
 *   1
 *   ...
 *   19
 * \endcode
 */

#define N 8
#define NB_ITEMS 20

int tampon[N];
int in = 0, out = 0;           /* circular indices */

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t non_plein = PTHREAD_COND_INITIALIZER;
pthread_cond_t non_vide  = PTHREAD_COND_INITIALIZER;
int nb = 0;                    /* occupied slots */

void deposer(int x) {
    tampon[in] = x;
    in = (in + 1) % N;
}

int retirer(void) {
    int x = tampon[out];
    out = (out + 1) % N;
    return x;
}

void *producteur(void *a) {
    (void) a;
    for (int i = 0; i < NB_ITEMS; i++) {
        pthread_mutex_lock(&m);
        while (nb == N) {
            pthread_cond_wait(&non_plein, &m);
        }
        deposer(i);
        nb++;
        pthread_cond_signal(&non_vide);
        pthread_mutex_unlock(&m);
    }
    return NULL;
}

void *consommateur(void *a) {
    (void) a;
    for (int k = 0; k < NB_ITEMS; k++) {
        pthread_mutex_lock(&m);
        while (nb == 0) {
            pthread_cond_wait(&non_vide, &m);
        }
        int x = retirer();
        nb--;
        pthread_cond_signal(&non_plein);
        pthread_mutex_unlock(&m);
        printf("%d\n", x);     /* outside the critical section */
    }
    return NULL;
}

int main(void) {
    pthread_t prod, cons;
    int err;

    if ((err = pthread_create(&prod, NULL, producteur, NULL)) != 0 ||
        (err = pthread_create(&cons, NULL, consommateur, NULL)) != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = pthread_join(prod, NULL)) != 0 ||
        (err = pthread_join(cons, NULL)) != 0) {
        fprintf(stderr, "pthread_join : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
various/src/without_synchro.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 <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

/**
 * @file without_synchro.c
 *
 * This program demonstrates inter-process communication using shared memory
 * in a Unix-like environment. It creates a shared integer variable and 
 * decrements this value in a critical section until it reaches zero, with
 * both parent and child processes participating in the decrement operation.
 *
 * WARNING: synchronization is deliberately missing. The test and the
 * decrement of the shared value are not atomic, so both processes may read
 * the same value (lost update, the same value displayed twice) or both
 * decrement it when it is 1 (the value becomes negative).
 * See ../../semaphores/src to protect such a critical section.
 */

#define SHM_SIZE sizeof(int)

int ended = 0;

void critical_section(int *value) {
    if (*value <= 0) {      /* <= : the race may make it negative */
        ended = 1;
    } else {
        *value = *value - 1;
        fprintf(stdout, "%ld has decremented value to: %d\n",
                (long) getpid(), *value);
    }
}

void random_delay(int at_least_ms, int at_most_ms) {
    int range = at_most_ms - at_least_ms;
    long ms = at_least_ms + rand() % range;
    struct timespec delay = { ms / 1000, (ms % 1000) * 1000000L };

    nanosleep(&delay, NULL);
}

int main(void) {
    int fd;
    int *ptr;
    pid_t pid;

    fd = shm_open("/blabla", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        perror("shm_open error");
        exit(EXIT_FAILURE);
    }

    if (ftruncate(fd, SHM_SIZE) == -1) {
        perror("ftruncate error");
        exit(EXIT_FAILURE);
    }

    ptr = (int *) mmap(NULL, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (ptr == MAP_FAILED) {
        perror("mmap error");
        exit(EXIT_FAILURE);
    }
    close(fd);

    *ptr = 20;

    pid = fork();
    if (pid == -1) {
        perror("fork error");
        exit(EXIT_FAILURE);
    }
    srand((unsigned int) getpid());  /* different delays in each process */

    while (!ended) {
        critical_section(ptr);
        random_delay(1, 50);
    }

    munmap(ptr, SHM_SIZE);
    if (pid > 0) {
        wait(NULL);         /* collects the child */
        shm_unlink("/blabla");
    }

    return EXIT_SUCCESS;
}