Skip to content

Interprocess Examples

Pipes

This sub-section contains examples related to the use of pipes for interprocess communication in C. Below is a list of the source files with links to their content.

File Name Description Link
anonymous_pipe_01.c Parent and child communicate through an anonymous pipe View
anonymous_pipe_02.c Parent and child communicate through an anonymous pipe View
pipe_supervisor.c Supervisor: runs a command in a child whose standard output goes into a pipe, reads it with poll() until a deadline (CLOCK_MONOTONIC), then kills the whole process group of the child (setpgid(), kill(-pid, SIGKILL)) if needed, and decodes its status. Without arguments, a demonstration of four cases: success, too slow, failure, and a background process that keeps the pipe open View
color_changer.c Gtk process that creates the named pipe colorpipe and changes its background color based on its input (run it first) View
color_sender.c Process that sends background color to color_changer through a named pipe View
mkfifo_client.c Client that sends a request to a server through a named pipe View
mkfifo_server.c Server that returns the result of a calculation request sent by a client through two FIFOs; ignores SIGPIPE so that it can remove the FIFOs if the client leaves View
mkfifo_producer.c Producer that creates the named pipe testfifo (accepts EEXIST) and sends a message through it View
mkfifo_consumer.c Consumer that reads a message from a named pipe until EOF, then removes it with unlink() View
pipe_ls_grep.c Reproduces the shell pipeline ls \| grep txt with pipe(), two fork(), dup2() and execlp() (course, chapter "Tubes") View
pipe_deadlock.c Deadlock with two pipes: parent and child both read first; an alarm of DELAY seconds ends the demonstration (course, chapter "Tubes") View

POSIX Message Queues

This sub-section contains examples related to the use of POSIX message queues for interprocess communication in C. Below is a list of the source files with links to their content.

File Name Description Link
message_sender.c Sends messages to message_viewer throught a message queue View
message_viewer.c Receives messages from message_sender throught a message queue View
posix_msg_receiver.c A Receiver process using POSIX mqueue View
posix_msg_sender.c A sender process using POSIX mqueue: creates the queue, sends timestamps until Ctrl-C, then removes it with mq_unlink() View
mq_news_receiver.c Creates the queue /news, receives one message with its priority, then calls mq_unlink() (Linux; macOS through macosx_mqueue) (course, chapter "Files de messages") View
mq_news_sender.c Sends one message with a given priority to /news (./mq_news_sender 10 BBB) (Linux; macOS through macosx_mqueue) (course, chapter "Files de messages") View

Shared Memory

This sub-section contains examples related to the use of shared memory for interprocess communication in C. Below is a list of the source files with links to their content.

File Name Description Link
color_displayer.c Gtk window that changes its background color when a shared memory is modified View
color_modifier.c Process that writes random colors to a shared memory read by color_displayer (no synchronization; matrix size between 1 and 800; needs GTK 3 for the displayer) View
mmap_buffer_01.c Parent and child share one integer in an anonymous mapping, without synchronization (sleep() only) View
mmap_buffer_02.c Producer-consumer with a circular buffer in shared memory and active waiting (no semaphore) View
mmap_buffer_03.c Same as mmap_buffer_02.c but synchronized with two System V semaphores (functions P() and V()) View
mmap_buffer_04.c Several producers and consumers on the same buffer: two counting semaphores plus a mutex semaphore (System V, P()/V()) View
posix_shm_client.c A client sharing memory with a server (client version) View
posix_shm_server.c A client sharing memory with a server (server version) View
posix_shm_simple_1.c Example using parent and child processes sharing memory View
posix_shm_simple_2.c Another example using parent and child processes sharing memory View
posix_shm_simple_3.c Parent and child processes sharing a structure of one page (/pipeautique_simple3; PAGESIZE fixed to 4096: fails on macOS Apple Silicon, whose pages are 16 KiB) View
unix_shm.c Child processes IPC/sharing System V memory and POSIX semaphore View
unix_shm_consumer.c Consumer using an IPC/System V shared memory View
unix_shm_producer.c Producer using an IPC/System V shared memory View
posix_shm_spacebattle.c Example 1: creates, sizes, projects and frees a POSIX shared memory segment (course, chapter "Mémoire partagée") View
posix_shm_creator.c Creator of the segment /exemple: writes a value and a message, waits for Enter, then removes it (course, chapter "Mémoire partagée") View
posix_shm_consumer.c Consumer reading the existing segment /exemple read-only (checks its size first) (course, chapter "Mémoire partagée") View
posix_shm_fork_wait.c Example 2: the child writes 25 integers into the segment, the parent waits for it, then reads (course, chapter "Mémoire partagée") View
posix_shm_two_pages.c Example 3: segment of two pages projected twice (offset from sysconf(_SC_PAGESIZE)), exchange between parent and child (course, chapter "Mémoire partagée") View
posix_shm_ping_pong.c Parent/child ping-pong synchronized by two anonymous semaphores placed in the segment (Linux only: sem_init() is not implemented on macOS) (course, chapter "Mémoire partagée") View

Signal Handling

This sub-section contains examples related to signal handling for interprocess communication in C. Below is a list of the source files with links to their content.

File Name Description Link
signal_01.c Defines the new handler of the SIGINT signal View
signal_02.c Handles SIGALRM View
signal_03.c Handles SIGALRM to create a clock View
signal_04.c Handles SIGCHLD (handler installed before fork()): the parent works until its child has ended, without leaving a zombie View
signal_05.c Handles many signals View
signal_06.c Manages masks to block signals View
signal_07.c Handles SIGUSR1 View
signal_08a.c Handles SIGUSR1 without masking other signals View
signal_08b.c Handles SIGUSR1 and masking other signals View
signal_08c.c Variant of signal_08a/b: handles SIGUSR1 and SIGUSR2 with distinct handlers View
signal_09.c Sets up a signal handler with 3 arguments including siginfo_t View
signal_kill_child.c The parent sends SIGUSR1 to its child with kill(); the default action kills the child (course, chapter "Signaux") View
signal_sigsuspend.c Waits for SIGUSR1 without race condition: sigprocmask() + sigsuspend() and a volatile sig_atomic_t flag (course, chapter "Signaux") View
daemon_double_fork.c Creates a daemon with the double fork technique and setsid(); stops on SIGTERM (course, chapter "Signaux", part "Démons") View

Timer Handling

This sub-section contains examples related to timer handling for interprocess communication in C. Below is a list of the source files with links to their content.

File Name Description Link
linux_clock.c Handles POSIX timer to create a clock (Linux only: timer_create(), SIGRTMIN; see signal_03.c) View
macosx_clock.c Handles timer to create a clock (see signal_03.c) View
posix_timer_tic.c POSIX timer on CLOCK_MONOTONIC notifying SIGRTMIN: prints tic after 1.02 s, then every 500 ms (Linux) (course, chapter "Signaux", part "Minuteries POSIX") View

IPC/System V Messages

This sub-section contains examples related to the use of IPC/System V message queues for interprocess communication in C. Below is a list of the source files with links to their content.

File Name. Description Link
message.c Creates and displays messages (used by all programs) View
test_message.c Tests the message creation and display functions View
unix_msg_recv.c Receives a message through a System V queue; -r removes the queue afterwards (msgctl(IPC_RMID)) View
unix_msg_send.c Sends a message (at most 1023 characters) through a System V queue (created if needed) View

Sources

pipes/src/anonymous_pipe_01.c

View on GitHub

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

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

/**
 * @file anonymous_pipe_01.c
 *
 * A simple program that uses an anonymous pipe between a parent and its child.
 */

#define PIPE_INPUT  1
#define PIPE_OUTPUT 0
#define KEYBOARD    0
#define BYTE_SIZE   1

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

/**
 * Manages the parent process. It reads characters from keyboard and writes
 * them in the pipe.
 * @param pipe The anonymous pipe descriptors.
 */
void manage_parent(int pipe[]) {
    char byte;
    ssize_t ret;

    printf("Parent process (PID %ld)\n", (long) getpid());
    close(pipe[PIPE_OUTPUT]);

    do {
        ret = read(KEYBOARD, &byte, BYTE_SIZE);
        if (ret == -1) {
            perror("Error reading from keyboard");
            break;
        } else if (ret != 0) {
            if (isalnum((unsigned char) byte)) {
                if (write(pipe[PIPE_INPUT], &byte, BYTE_SIZE) == -1) {
                    perror("Error writing to pipe");
                    break;
                }
            }
        }
    } while (ret > 0);
    close(pipe[PIPE_INPUT]);

    wait(NULL);
    printf("Parent: has received child termination.\n");
}

/**
 * Manages the child process. Reads bytes from the pipe, counts letters and
 * numeral digits and displays the result.
 * @param pipe The anonymous pipe descriptors
 */
void manage_child(int pipe[]) {
    char byte;
    int letters = 0, digits = 0;
    ssize_t ret;

    printf("Child process (PID %ld)\n", (long) getpid());
    printf("Enter Ctrl-D (EOF) to end.\n");
    close(pipe[PIPE_INPUT]);

    while ((ret = read(pipe[PIPE_OUTPUT], &byte, BYTE_SIZE)) > 0) {
        if (isdigit((unsigned char) byte)) {
            digits++;
        } else if (isalpha((unsigned char) byte)) {
            letters++;
        }
    }
    if (ret == -1) {
        perror("Error reading from pipe");
    }

    printf("\n%d digits received\n", digits);
    printf("%d letters received\n", letters);
}

int main(void) {
    pid_t pid;
    int anonymous_pipe[2]; /* pipe descriptors */

    if (pipe(anonymous_pipe) == -1) {
        handle_fatal_error("Error [pipe()]");
    }

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

    return EXIT_SUCCESS;
}
pipes/src/anonymous_pipe_02.c

View on GitHub

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

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

/**
 * @file anonymous_pipe_02.c
 *
 * Another simple program that uses an anonymous pipe between a parent and its
 * child.
 */

#define PIPE_INPUT    1
#define PIPE_OUTPUT   0
#define KEYBOARD      0
#define STOP         -1
#define INTEGER_SIZE  sizeof(int)
#define BUFFER_SIZE   100

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

/**
 * Manages the parent process. It reads integers from keyboard ans writes
 * them in the pipe. It sends -1 to stop communication.
 * @param pipe The anonymous pipe descriptors
 */
void manage_parent(int pipe[]) {
    int integer;
    char buffer[BUFFER_SIZE];

    printf("Parent process (PID %ld)\n", (long) getpid());
    close(pipe[PIPE_OUTPUT]);

    while (1) {
        if (fgets(buffer, BUFFER_SIZE, stdin) == NULL) {
            break; /* Break on EOF or error */
        }
        if (sscanf(buffer, "%d", &integer) != 1) {
            fprintf(stderr, "Invalid input\n");
            continue;
        }
        if (write(pipe[PIPE_INPUT], &integer, INTEGER_SIZE) == -1) {
            perror("Error writing to pipe");
            break;
        }
        if (integer == STOP) {
            break;
        }
    }
    close(pipe[PIPE_INPUT]);

    wait(NULL);
    printf("Parent: has received child termination.\n");
}

/**
 * Manages the child process. Reads integers from the pipe and displays them.
 * It stops when receiving -1.
 * @param pipe The anonymous pipe descriptors
 */
void manage_child(int pipe[]) {
    int integer;
    ssize_t bytesRead;

    printf("Child process (PID %ld)\n", (long) getpid());
    close(pipe[PIPE_INPUT]);

    while (1) {
        bytesRead = read(pipe[PIPE_OUTPUT], &integer, INTEGER_SIZE);
        if (bytesRead == -1) {
            perror("Error reading from pipe");
            break;
        }
        if (bytesRead == 0) { /* Pipe is closed */
            break;
        }
        printf("\nValue received: %d\n", integer);
        if (integer == STOP) {
            break;
        }
    }
    close(pipe[PIPE_OUTPUT]);
    printf("Child has finished.\n");
}

int main(void) {
    pid_t pid;
    int anonymous_pipe[2]; /* pipe descriptors */

    if (pipe(anonymous_pipe) == -1) {
        handle_fatal_error("Error [pipe()]");
    }

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

    return EXIT_SUCCESS;
}
pipes/src/color_changer.c

View on GitHub

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <gtk/gtk.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

/**
 * @file color_changer.c
 * @brief A program that changes its background color based on input from a
 * named pipe.
 *
 * This program, color_changer.c, is a GTK-based application that creates 
 * a window and continuously reads color values from a named pipe. It changes
 * its background color to match the received color values, providing a 
 * dynamic visual display of colors. When receiving "FIN", it unlinks the 
 * pipe and terminates.
 */

#define COLORPIPE "colorpipe"
#define COLOR_NAME_SIZE 50

typedef struct {
    GtkWidget *window;
    int pipe_fd;
} ThreadData;

void set_window_color(gpointer user_data) {
    ThreadData *thread_data;
    GtkWidget *window;
    int pipe_fd;
    char color_name[COLOR_NAME_SIZE];
    ssize_t bytes_read;

    thread_data = (ThreadData *) user_data;
    window = thread_data->window;
    pipe_fd = thread_data->pipe_fd;

    while ((bytes_read = read(pipe_fd, color_name, sizeof(color_name))) > 0) {
        color_name[bytes_read - 1] = '\0'; /* Termine la chaîne (color_sender envoie déjà le '\0') */

        /* Teste si le mot reçu est le mot-clé "FIN" de manière à quitter */
        if (strcmp(color_name, "FIN") == 0) {
            break;
        }

        GdkRGBA color;
        gdk_rgba_parse(&color, color_name);

        /* Met à jour la couleur pour le thread principal */
        gdk_threads_enter();
        gtk_widget_override_background_color(window, GTK_STATE_FLAG_NORMAL, &color);
        gtk_widget_queue_draw(window);
        gdk_threads_leave();
    }

    /* Ferme et détruit le tube nommé */
    close(pipe_fd);
    unlink(COLORPIPE);

    /* Sort de la boucle principale de GTK */
    gdk_threads_enter();
    gtk_main_quit();
    gdk_threads_leave();
}

gpointer thread_func(gpointer user_data) {
    set_window_color(user_data);
    return NULL;
}

int main(int argc, char *argv[]) {
    gtk_init(&argc, &argv);

    GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(window), "Color Changer");
    gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);

    g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);

    /* Crée le tube nommé (EEXIST : il existe déjà, on l'utilise) */
    if (mkfifo(COLORPIPE, 0600) == -1 && errno != EEXIST) {
        perror("Error creating the pipe");
        exit(EXIT_FAILURE);
    }

    int pipe_fd = open(COLORPIPE, O_RDONLY);
    if (pipe_fd == -1) {
        perror("Error opening the pipe for reading");
        exit(EXIT_FAILURE);
    }

    ThreadData thread_data;
    thread_data.window = window;
    thread_data.pipe_fd = pipe_fd;

    /* Initialise le support des threads pour GTK */
    if (!g_thread_supported()) {
        g_thread_init(NULL);
        gdk_threads_init();
    }

    gdk_threads_enter();

    /* 
     * Crée un thread pour la lecture de la couleur depuis le tube. Ceci est
     * nécessaire afin de libérer le thread principal de cette tâche.
     */
    GThread *pipe_thread = g_thread_new("PipeThread", thread_func, &thread_data);

    gtk_widget_show_all(window);

    gdk_threads_leave();

    gtk_main();

    g_thread_unref(pipe_thread);

    return EXIT_SUCCESS;
}
pipes/src/color_sender.c

View on GitHub

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

/**
 * @file color_sender.c
 *
 * @brief A program to send color values to a named pipe.
 *
 * This program, color_sender.c, is a C application that reads color values 
 * from the user and sends them to a named pipe. It is part of a system where
 * another program (color_changer.c) reads these color values from the pipe
 * and changes its background color accordingly.
 *
 * To use the Color Sender program, first run color_changer (which creates
 * the named pipe), then run it from the command line. It will 
 * prompt the user to enter color values. Once a color value is entered, it 
 * will be sent to the named pipe for the Color Changer program to read and 
 * act upon. The word "FIN" will send a termination order to the Color Changer
 * program and will exit.
 *
 * Example usage:
 * ./color_sender
 * Enter a color name (e.g., red, green, blue): red
 * Enter a color name (e.g., red, green, blue): green
 * Enter a color name (e.g., red, green, blue): FIN
 */

#define COLORPIPE "colorpipe"
#define COLOR_NAME_SIZE 50

void trim_newline(char *str) {
    size_t len = strlen(str);
    if (len > 0 && str[len - 1] == '\n') {
        str[len - 1] = '\0';
    }
}

int main(void) {
    int pipe_fd = open(COLORPIPE, O_WRONLY);
    if (pipe_fd == -1) {
        perror("Error opening pipe for writing");
        exit(EXIT_FAILURE);
    }

    char color_name[COLOR_NAME_SIZE];
    ssize_t bytes_written;

    while(1) {
        printf("Enter a color name (e.g., red, green, blue): ");
        if (fgets(color_name, sizeof(color_name), stdin) == NULL) {
            snprintf(color_name, sizeof(color_name), "FIN"); /* EOF (Ctrl-D): also stop color_changer */
        }
        trim_newline(color_name); /* Suppression du caractère de fin de ligne */

        /* Ecriture de la couleur vers le tube */
        bytes_written = write(pipe_fd, color_name, strlen(color_name) + 1);
        if (bytes_written == -1) {
            perror("Error writing to pipe");
            close(pipe_fd);
            exit(EXIT_FAILURE);
        }

        /* Teste si l'entrée est le mot-clé "FIN" de manière à quitter */
        if (strcmp(color_name, "FIN") == 0) {
            break;
        }
    }

    close(pipe_fd);

    return EXIT_SUCCESS;
}
pipes/src/mkfifo_client.c

View on GitHub

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

/**
 * @file mkfifo_client.c
 *
 * A client program that sends a request to a server to calculate a <op> b.
 * They both communicate using two fifos.
 */

#define QUESTION "cli2serv"
#define RESPONSE "serv2cli"

/**
 * Reads the expression "a <op> b" from stdin and sends it to the server
 * through the named pipe of given descriptor \c fdq. The response from the
 * server is read from the named pipe of given descriptor \c fdr and is
 * send to stdout. The function exit when receiving "OK".
 * @param fdr The descriptor of the named pipe for the response from the server.
 * @param fdq The descriptor of the named pipe to send queries to the server.
 */
void manage_client(int fdr, int fdq);

int main(void) {
    int fdq;
    int fdr;

    fdq = open(QUESTION, O_WRONLY);
    if (fdq == -1) {
        fprintf(stderr, "Unable to access to input named pipe %s\n", QUESTION);
        fprintf(stderr, "Please, run server first!\n");
        exit(EXIT_FAILURE);
    }

    fdr = open(RESPONSE, O_RDONLY);
    if (fdr == -1) {
        fprintf(stderr, "Unable to access to output named pipe %s\n", RESPONSE);
        fprintf(stderr, "Please, run server first!\n");
        exit(EXIT_FAILURE);
    }

    manage_client(fdr, fdq);

    close(fdq);
    close(fdr);

    return EXIT_SUCCESS;
}

void manage_client(int fdr, int fdq) {
    char response[12]; /* the server sends up to 11 bytes: 10 chars + '\0' */
    char query[11];
    ssize_t bytes_written, bytes_read;

    while (1) {
        printf("Enter expression (a <op> b): ");
        if (fgets(query, 11, stdin) == NULL) {
            break; /* EOF (Ctrl-D): closing the pipes also stops the server */
        }
        bytes_written = write(fdq, query, strlen(query));
        if (bytes_written == -1) {
            perror("Error writing to pipe");
            break;
        }

        /* One read() = one response: true here because the server answers each
           short request before the next one (a pipe is a byte stream) */
        bytes_read = read(fdr, response, sizeof(response) - 1);
        if (bytes_read == -1) {
            perror("Error reading from pipe");
            break;
        }
        if (bytes_read == 0) { /* EOF: the server has closed the pipe */
            break;
        }
        response[bytes_read] = '\0'; /* Null-terminate the response */

        printf("Client -> %s\n", query);
        printf("Server -> %s\n", response);

        if (strcmp(response, "OK") == 0) {
            break;
        }
    }
}
pipes/src/mkfifo_consumer.c

View on GitHub

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

/**
 * @file mkfifo_consumer.c
 *
 * A consumer program that uses a named pipe (mkfifo) to receive messages 
 * from a producer.
 */

#define BUFFER_SIZE 100

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

/**
 * Open the pipe with the specified name in a read only mode.
 * @param name Name of the pipe.
 * @return The pipe descriptor.
 */
int open_pipe(const char *name) {
    int pd;

    pd = open(name, O_RDONLY);
    if (pd == -1) {
        handle_fatal_error("Error [open()]");
    }
    return pd;
}

int main(void) {
    char buffer[BUFFER_SIZE] = {0};
    int pd;
    ssize_t message_length;

    pd = open_pipe("testfifo");

    printf("\nRead message from the pipe...\n");
    /* A read may return only part of the message: read until 0 (EOF) */
    while ((message_length = read(pd, buffer, BUFFER_SIZE - 1)) > 0) {
        buffer[message_length] = '\0'; /* space kept for null terminator */
        printf("%s", buffer);
    }
    printf("\n");
    if (message_length == -1) {
        handle_fatal_error("Error [read()]");
    }

    close(pd);
    unlink("testfifo"); /* removes the name of the pipe (like rm) */

    return EXIT_SUCCESS;
}
pipes/src/mkfifo_producer.c

View on GitHub

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

/**
 * @file mkfifo_producer.c
 *
 * A producer program that uses a named pipe (FIFO) to send messages to a
 * consumer.
 */

#define BUFFER_SIZE 100

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

/**
 * Creates a named pipe.
 * @param name Name of the pipe.
 * @param mode Permissions access.
 * @return The pipe identifier.
 */
int create_pipe(const char *name, mode_t mode) {
    /* EEXIST: the pipe already exists (previous run), we can use it */
    if (mkfifo(name, mode) == -1 && errno != EEXIST) {
        handle_fatal_error("Error [mkfifo()]");
    }
    return 0; /* If mkfifo is successful */
}

/**
 * Open the pipe with the specified name in a write only mode.
 * @param name Name of the pipe.
 * @return The pipe descriptor.
 */
int open_pipe(const char *name) {
    int pd = open(name, O_WRONLY);
    if (pd == -1) {
        handle_fatal_error("Error [open()]");
    }
    return pd;
}

int main(void) {
    char buffer[BUFFER_SIZE] = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium...";
    ssize_t bytes_written;

    /*
     * Create a new pipe named "testfifo" with read/write permissions for owner,
     * and with read permissions for group and others. open() blocks until
     * the consumer opens the pipe for reading.
     */
    create_pipe("testfifo", S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
    int pd = open_pipe("testfifo");

    bytes_written = write(pd, buffer, strlen(buffer));
    if (bytes_written == -1) {
        handle_fatal_error("Error writing to pipe");
    }

    close(pd);
    /* The consumer removes the name with unlink() once the message is read */

    return EXIT_SUCCESS;
}
pipes/src/mkfifo_server.c

View on GitHub

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

/**
 * @file mkfifo_server.c
 *
 * A server program that returns the result of a a+b request sent by a client.
 * They both communicate using fifos.
 *
 * Simplification: each read() is taken as one whole request. A pipe is a
 * stream of bytes, so this holds only because requests are short and the
 * client waits for each response before sending the next one.
 */

#define QUESTION "cli2serv"
#define RESPONSE "serv2cli"
/* SECURITY NOTE: predictable FIFO names in shared directories are vulnerable to local attacks.
 * Production code should use private directories, strict permissions, and peer validation. */

/**
 * Reads the expression "a <op> b" (op = '+', '-', '*' or '/') from the
 * the named pipe of given descriptor \c fdq and calculates it. The response
 * is sent to the named pipe of given descriptor \c fdr. The server stops when
 * receiving the string "Pouce!".
 * @param fdr The descriptor of the named pipe for the response to the client.
 * @param fdq The descriptor of the named pipe to receive queries from the client.
 */
void manage_server(int fdr, int fdq);

int main(void) {
    int fdq;
    int fdr;

    /* If the client leaves, write() fails with EPIPE instead of killing the
       server with SIGPIPE: the server can then remove the FIFOs */
    signal(SIGPIPE, SIG_IGN);

    unlink(QUESTION);
    unlink(RESPONSE);

    /* Création des tubes nommés */
    if (mkfifo(QUESTION, 0644) == -1 || mkfifo(RESPONSE, 0644) == -1) {
        perror("Impossible de créer les tubes");
        exit(EXIT_FAILURE);
    }

    /* Attente des ouvertures Clients */
    fdq = open(QUESTION, O_RDONLY);
    if (fdq == -1) {
        fprintf(stderr, "Unable to access to input named pipe %s\n", QUESTION);
        exit(EXIT_FAILURE);
    }

    fdr = open(RESPONSE, O_WRONLY);
    if (fdr == -1) {
        fprintf(stderr, "Unable to access to output named pipe %s\n", RESPONSE);
        exit(EXIT_FAILURE);
    }

    manage_server(fdr, fdq);

    close(fdq);
    close(fdr);

    unlink(QUESTION);
    unlink(RESPONSE);

    return EXIT_SUCCESS;
}

void manage_server(int fdr, int fdq) {
    int operand1, operand2, result = 0;
    const char *error;
    char operator;
    char question[11];
    char response[11];
    ssize_t bytes_read, bytes_written;

    while (1) {
        bytes_read = read(fdq, question, 10);
        if (bytes_read == -1) {
            perror("Error reading from pipe");
            break;
        }
        if (bytes_read == 0) { /* EOF: the client has closed the pipe */
            break;
        }
        question[bytes_read] = '\0'; /* Null-terminate the question */

        if (strncmp(question, "Pouce!", 6) == 0) {
            snprintf(response, sizeof(response), "OK");
            if (write(fdr, response, strlen(response) + 1) == -1) { /* +1 for '\0' */
                perror("Error writing to pipe");
            }
            break;
        }

        /* SECURITY NOTE: parse the operator as a char to avoid writing a string
         * into one-byte storage. In production, also validate input length/range. */
        if (sscanf(question, "%d %c %d", &operand1, &operator, &operand2) < 3) {
            snprintf(response, sizeof(response), "Error");
        } else {
            error = NULL;
            switch (operator) {
                case '+' :
                    result = operand1 + operand2;
                    break;
                case '-' :
                    result = operand1 - operand2;
                    break;
                case '*' :
                    result = operand1 * operand2;
                    break;
                case '/' :
                    if (operand2 == 0) {
                        error = "NaN";
                    } else {
                        result = operand1 / operand2;
                    }
                    break;
                default :
                    /* No 'continue': the client waits for a response */
                    error = "Invalid Op";
                    break;
            }

            if (error != NULL) {
                snprintf(response, sizeof(response), "%s", error);
            } else {
                snprintf(response, sizeof(response), "%d", result);
            }
        }

        bytes_written = write(fdr, response, strlen(response) + 1);
        if (bytes_written == -1) {
            perror("Error writing to pipe");
            break;
        }
    }
}
pipes/src/pipe_deadlock.c

View on GitHub

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

/**
 * @file pipe_deadlock.c
 * @brief Deadlock between a parent and its child using two pipes.
 *
 * Course "Operating Systems", chapter "Tubes", slides
 * "Interblocage (deadlock)" and "Interblocage : attente circulaire".
 *
 * t1 carries data from the parent to the child, t2 from the child to the
 * parent. Each process first waits for the other one (read), and nobody
 * writes as long as it has not read: circular wait, mutual blocking.
 *
 * Addition to the slide: an alarm of DELAY seconds lets the parent detect
 * the deadlock, kill the child and stop, instead of blocking forever.
 * Fix: a request/response protocol stating who speaks first (e.g. the
 * parent writes, then reads the response).
 *
 * \code{.bash}
 *   $ ./pipe_deadlock
 *   Parent and child are both waiting for each other...
 *   Deadlock: no data after 3 s, the parent kills its child.
 * \endcode
 */

#define DELAY 3

/* Written by main() before alarm() starts the timer, so before the handler can
   run: the handler only reads it (a pid_t is not a sig_atomic_t) */
static volatile pid_t child_pid = 0;

/**
 * @brief Handler of SIGALRM: only async-signal-safe calls (write, kill, _exit).
 * @param sig Number of the received signal.
 */
static void handle_alarm(int sig) {
    (void) sig;
    /* DELAY is a macro: the string is built at compile time (no printf() here) */
#define STR2(x) #x
#define STR(x) STR2(x)
    const char msg[] = "Deadlock: no data after " STR(DELAY) " s, the parent kills its child.\n";
    write(STDERR_FILENO, msg, sizeof(msg) - 1);
    if (child_pid > 0)
        kill(child_pid, SIGKILL);
    _exit(EXIT_FAILURE);
}

int main(void) {
    int t1[2], t2[2];   /* t1: parent -> child */
    char buf[64];       /* t2: child -> parent */
    struct sigaction sa;
    pid_t pid;

    if (pipe(t1) == -1 || pipe(t2) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    if (pid == 0) {
        close(t1[1]);                  /* unused ends */
        close(t2[0]);
        read(t1[0], buf, sizeof(buf)); /* waits */
        write(t2[1], "reponse", 7);
        exit(EXIT_SUCCESS);
    }

    close(t1[0]);                      /* unused ends */
    close(t2[1]);

    /* Addition: watchdog to end the demonstration */
    child_pid = pid;
    sa.sa_handler = handle_alarm;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGALRM, &sa, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }
    alarm(DELAY);

    printf("Parent and child are both waiting for each other...\n");
    fflush(stdout);

    read(t2[0], buf, sizeof(buf));     /* waits */
    write(t1[1], "requete", 7);

    /* Never reached */
    waitpid(pid, NULL, 0);
    return EXIT_SUCCESS;
}
pipes/src/pipe_ls_grep.c

View on GitHub

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

/**
 * @file pipe_ls_grep.c
 * @brief Reproduces the shell pipeline "ls | grep txt".
 *
 * Course "Operating Systems", chapter "Tubes", slides
 * "Pipeline (1/2) : enfant 1, ls" and "Pipeline (2/2) : enfant 2, grep,
 * et parent".
 *
 * The parent creates the pipe and two children:
 * - child 1 redirects its stdout to the write end, then executes ls;
 * - child 2 redirects its stdin to the read end, then executes grep txt.
 * The parent closes both ends: if it kept fd[1], grep would never read 0
 * (EOF) and would wait forever.
 *
 * \code{.bash}
 *   $ touch a.txt b.txt c.dat
 *   $ ./pipe_ls_grep
 *   a.txt
 *   b.txt
 * \endcode
 */

int main(void) {
    int fd[2];
    int status;

    if (pipe(fd) == -1) { perror("pipe"); exit(EXIT_FAILURE); }

    pid_t pid1 = fork();
    if (pid1 == -1) { perror("fork"); exit(EXIT_FAILURE); }
    if (pid1 == 0) {                /* child 1: ls */
        close(fd[0]);               /* read end unused */
        dup2(fd[1], STDOUT_FILENO); /* stdout -> pipe */
        close(fd[1]);
        execlp("ls", "ls", (char *) NULL);
        perror("execlp");           /* exec failed */
        _exit(127);
    }

    pid_t pid2 = fork();
    if (pid2 == -1) { perror("fork"); exit(EXIT_FAILURE); }
    if (pid2 == 0) {                /* child 2: grep */
        close(fd[1]);               /* write end unused */
        dup2(fd[0], STDIN_FILENO);  /* stdin <- pipe */
        close(fd[0]);
        execlp("grep", "grep", "txt", (char *) NULL);
        perror("execlp");
        _exit(127);
    }

    close(fd[0]);                   /* parent: does not use */
    close(fd[1]);                   /* the pipe */
    waitpid(pid1, NULL, 0);
    if (waitpid(pid2, &status, 0) == -1) {
        perror("waitpid");
        exit(EXIT_FAILURE);
    }

    /* Like the shell, return the status of the last command */
    return WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE;
}
pipes/src/pipe_supervisor.c

View on GitHub

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

#define _POSIX_C_SOURCE 200809L /* poll(), kill(), strsignal(), nanosleep() */
#include <errno.h>
#include <poll.h>      /* poll() */
#include <signal.h>    /* kill(), SIGKILL */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>    /* strsignal() */
#include <sys/types.h>
#include <sys/wait.h>  /* waitpid() */
#include <time.h>      /* clock_gettime(), nanosleep() */
#include <unistd.h>    /* fork(), pipe(), dup2(), execvp(), setpgid() */

/**
 * @file pipe_supervisor.c
 *
 * @brief Un superviseur : lance une commande dans un processus enfant,
 * capture sa sortie standard par un tube et l'arrête si elle dépasse un délai.
 *
 * Usage : ./bin/pipe_supervisor SECONDES commande [arguments...]
 *         ./bin/pipe_supervisor            (démonstration : trois commandes)
 *
 * Points à observer :
 * - l'enfant redirige sa sortie standard vers le tube avec dup2(), puis
 *   ferme les deux extrémités ; le parent ferme l'extrémité d'écriture, sans
 *   quoi il n'obtiendrait jamais la fin de fichier ;
 * - le délai est une échéance sur l'horloge CLOCK_MONOTONIC, que poll()
 *   respecte même si la commande n'écrit rien et ne ferme jamais sa sortie.
 *   Un read() bloquant, même interrompu par alarm(), ne le garantit pas : si
 *   la lecture reprend après EINTR, le parent reste bloqué ;
 * - l'enfant crée son propre groupe de processus (setpgid()) : à l'échéance,
 *   kill(-pid, SIGKILL) tue aussi les processus qu'il a lancés, qui
 *   pourraient garder le tube ouvert ;
 * - la sortie au-delà de la mémoire tampon est lue puis ignorée : un enfant
 *   bavard ne reste pas bloqué sur un tube plein ;
 * - l'état de l'enfant est décodé avec WIFEXITED() et WIFSIGNALED() ;
 *   127 signale, comme dans le shell, une commande introuvable.
 */

#define BUFFER_SIZE 256

/* Résultat de la supervision d'une commande. */
struct outcome {
    bool timed_out;          /* arrêtée par le superviseur à l'échéance */
    int status;              /* état renvoyé par waitpid() */
    char output[BUFFER_SIZE];/* début de la sortie standard, terminé par '\0' */
    bool truncated;          /* la sortie dépassait la mémoire tampon */
};

/* Millisecondes écoulées depuis une origine arbitraire mais fixe. */
static long long now_ms(void)
{
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return (long long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}

/* Lance argv[0] (cherché dans PATH) avec sa sortie standard dans le tube. */
static void run_child(int pipe_fd[2], char *argv[])
{
    setpgid(0, 0); /* son propre groupe : voir kill(-pid, ...) dans le parent */
    if (dup2(pipe_fd[1], STDOUT_FILENO) == -1) {
        perror("dup2");
        _exit(127);
    }
    close(pipe_fd[0]);
    close(pipe_fd[1]);
    execvp(argv[0], argv);
    perror(argv[0]); /* execvp() ne revient qu'en cas d'échec */
    _exit(127);
}

/*
 * Lit le tube jusqu'à la fin de fichier ou jusqu'à l'échéance. Renvoie 0 à la
 * fin de fichier, 1 si l'échéance est atteinte, -1 en cas d'erreur.
 */
static int read_until(int fd, long long deadline, struct outcome *out)
{
    size_t used = 0;
    char scratch[BUFFER_SIZE]; /* reçoit ce qui dépasse la mémoire tampon */

    for (;;) {
        long long left = deadline - now_ms();
        if (left <= 0) {
            out->output[used] = '\0';
            return 1;
        }
        struct pollfd p = { .fd = fd, .events = POLLIN };
        int ready = poll(&p, 1, (int)left);
        if (ready == -1) {
            if (errno == EINTR) {
                continue;
            }
            perror("poll");
            out->output[used] = '\0';
            return -1;
        }
        if (ready == 0) {
            continue; /* délai de poll() écoulé : la boucle constate l'échéance */
        }
        /* POLLIN, ou POLLHUP quand l'écrivain a fermé : read() tranche. */
        char *dest = scratch;
        size_t room = sizeof scratch;
        if (used + 1 < sizeof out->output) {
            dest = out->output + used;
            room = sizeof out->output - 1 - used;
        }
        ssize_t n = read(fd, dest, room);
        if (n == 0) {
            out->output[used] = '\0';
            return 0; /* fin de fichier : plus aucun écrivain */
        }
        if (n == -1) {
            if (errno == EINTR) {
                continue;
            }
            perror("read");
            out->output[used] = '\0';
            return -1;
        }
        if (dest == scratch) {
            out->truncated = true;
        } else {
            used += (size_t)n;
        }
    }
}

/* Attend l'enfant ; à l'échéance, tue son groupe. Renvoie 0, ou -1. */
static int wait_until(pid_t pid, long long deadline, struct outcome *out)
{
    const struct timespec pause = { .tv_sec = 0, .tv_nsec = 10 * 1000000 };

    for (;;) {
        pid_t w = waitpid(pid, &out->status, WNOHANG);
        if (w == pid) {
            return 0;
        }
        if (w == -1) {
            if (errno == EINTR) {
                continue;
            }
            perror("waitpid");
            return -1;
        }
        if (now_ms() >= deadline) {
            out->timed_out = true;
            kill(-pid, SIGKILL); /* tout le groupe de l'enfant */
            while (waitpid(pid, &out->status, 0) == -1 && errno == EINTR) {
            }
            return 0;
        }
        nanosleep(&pause, NULL); /* l'enfant a fermé sa sortie mais vit encore */
    }
}

/* Supervise argv pendant au plus seconds secondes. Renvoie 0, ou -1. */
static int supervise(char *argv[], int seconds, struct outcome *out)
{
    int pipe_fd[2];
    memset(out, 0, sizeof *out);

    if (pipe(pipe_fd) == -1) {
        perror("pipe");
        return -1;
    }
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        close(pipe_fd[0]);
        close(pipe_fd[1]);
        return -1;
    }
    if (pid == 0) {
        run_child(pipe_fd, argv);
    }
    setpgid(pid, pid); /* même appel que l'enfant : pas de course */
    close(pipe_fd[1]);

    long long deadline = now_ms() + 1000LL * seconds;
    int r = read_until(pipe_fd[0], deadline, out);
    close(pipe_fd[0]);
    if (r == 0) {
        return wait_until(pid, deadline, out); /* sortie fermée : attendre la fin */
    }
    /*
     * Échéance (r == 1) ou erreur (r == -1) avant la fin de fichier : un
     * processus du groupe garde le tube ouvert, peut-être un petit-enfant alors
     * que l'enfant a déjà fini. Tuer tout le groupe, puis attendre l'enfant.
     */
    out->timed_out = (r == 1);
    kill(-pid, SIGKILL);
    while (waitpid(pid, &out->status, 0) == -1 && errno == EINTR) {
    }
    return r == 1 ? 0 : -1;
}

/* Affiche le résultat ; renvoie true si la commande a réussi. */
static bool report(const char *name, const struct outcome *out)
{
    printf("%s : ", name);
    if (out->timed_out) {
        printf("arrêtée après le délai");
    } else if (WIFEXITED(out->status)) {
        printf("code de sortie %d", WEXITSTATUS(out->status));
    } else if (WIFSIGNALED(out->status)) {
        printf("tuée par le signal %d (%s)", WTERMSIG(out->status),
               strsignal(WTERMSIG(out->status)));
    }
    if (out->output[0] != '\0') {
        size_t len = strcspn(out->output, "\n"); /* la première ligne seulement */
        bool more = out->truncated
                    || (out->output[len] == '\n' && out->output[len + 1] != '\0');
        printf(", sortie : \"%.*s\"%s", (int)len, out->output, more ? " (...)" : "");
    }
    printf("\n");
    return !out->timed_out && WIFEXITED(out->status)
           && WEXITSTATUS(out->status) == 0;
}

/*
 * Quatre cas, chacun avec le résultat attendu : une réussite, une commande
 * trop longue, un échec, et une commande qui finit en laissant un processus
 * en arrière-plan garder le tube ouvert.
 */
static int demo(void)
{
    char *ok[] = { "sh", "-c", "echo TOKEN=bravo", NULL };
    char *slow[] = { "sh", "-c", "sleep 30; echo trop tard", NULL };
    char *fails[] = { "sh", "-c", "echo erreur; exit 3", NULL };
    char *orphan[] = { "sh", "-c", "echo lancé; sleep 30 &", NULL };
    struct outcome out;
    bool expected = true;
    long long start = now_ms();

    if (supervise(ok, 2, &out) == -1) {
        return EXIT_FAILURE;
    }
    expected &= report("réussite", &out);

    if (supervise(slow, 1, &out) == -1) {
        return EXIT_FAILURE;
    }
    report("lente", &out);
    expected &= out.timed_out;

    if (supervise(fails, 2, &out) == -1) {
        return EXIT_FAILURE;
    }
    expected &= !report("échec", &out)
                && WIFEXITED(out.status) && WEXITSTATUS(out.status) == 3;

    if (supervise(orphan, 1, &out) == -1) {
        return EXIT_FAILURE;
    }
    report("arrière-plan", &out);
    expected &= out.timed_out;

    printf("durée totale : %.1f s (deux délais de 1 s)\n",
           (double)(now_ms() - start) / 1000.0);
    return expected ? EXIT_SUCCESS : EXIT_FAILURE;
}

int main(int argc, char *argv[])
{
    if (argc == 1) {
        return demo();
    }
    char *end;
    long seconds = strtol(argv[1], &end, 10);
    if (argc < 3 || *end != '\0' || seconds < 1 || seconds > 3600) {
        fprintf(stderr, "Usage : %s SECONDES commande [arguments...]\n", argv[0]);
        return EXIT_FAILURE;
    }
    struct outcome out;
    if (supervise(argv + 2, (int)seconds, &out) == -1) {
        return EXIT_FAILURE;
    }
    return report(argv[2], &out) ? EXIT_SUCCESS : EXIT_FAILURE;
}
posix_messages/src/message_sender.c

View on GitHub

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

#ifdef __APPLE__
#include "macosx/mqueue.h"
#elif __linux__
#include <mqueue.h>
#endif

/**
 * @file message_sender.c
 * @brief Send messages throught a message queue.
 */

#define QUEUE_NAME "/myqueue"
#define MAX_MSG_SIZE 1024

typedef struct {
    char sentence[MAX_MSG_SIZE];
    int priority;
} Message;

int main(void) {
    mqd_t mq;
    struct mq_attr attr;
    Message msg;
    int c;

    mq_unlink(QUEUE_NAME); /* Removes a queue left by a previous run, so that it
                            * is recreated with the attributes below */

    /* Open the message queue */
    memset(&attr, '\0', sizeof(attr));
    attr.mq_flags = 0;
    attr.mq_maxmsg = 10; /* Maximum number of messages in the queue */
    attr.mq_msgsize = sizeof(Message); /* Maximum message size */
    attr.mq_curmsgs = 0;

    mq = mq_open(QUEUE_NAME, O_CREAT | O_WRONLY, 0600, &attr);
    if (mq == (mqd_t) - 1) {
        perror("mq_open");
        exit(EXIT_FAILURE);
    }

    while (1) {
        printf("Enter a sentence (or 'exit' to quit): ");
        if (fgets(msg.sentence, MAX_MSG_SIZE, stdin) == NULL) {
            break; /* EOF (Ctrl-D): otherwise the loop would never end */
        }

        if (strcmp(msg.sentence, "exit\n") == 0) {
            break;
        }

        printf("Enter priority (0-9): ");
        if (scanf("%d", &msg.priority) != 1 || msg.priority < 0 || msg.priority > 9) {
            fprintf(stderr, "Invalid priority. Please enter a number between 0 and 9.\n");
            while ((c = getchar()) != '\n' && c != EOF) {
                ; /* Consume the rest of the invalid line */
            }
            continue;
        }
        getchar(); /* Consume newline */

        /* Send the message to the queue */
        if (mq_send(mq, (const char *) &msg, sizeof(Message), msg.priority) == -1) {
            perror("mq_send");
            continue;
        }
    }

    /* Close and unlink the message queue */
    mq_close(mq);
    mq_unlink(QUEUE_NAME);

    return EXIT_SUCCESS;
}
posix_messages/src/message_viewer.c

View on GitHub

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

#ifdef __APPLE__
#include "macosx/mqueue.h"
#elif __linux__
#include <mqueue.h>
#endif

/**
 * @file message_viewer.c
 * @brief Receive messages throught a message queue.
 */

#define QUEUE_NAME "/myqueue"

typedef struct {
    char sentence[1024];
    int priority;
} Message;

GtkWidget *window;
GtkWidget *grid;

/* An array to keep track of message labels for each priority */
GtkWidget *message_labels[10] = {NULL};

void display_message(Message msg) {
    if (msg.priority < 0 || msg.priority >= 10) {
        fprintf(stderr, "Invalid message priority: %d\n", msg.priority);
        return;
    }

    /* Remove the old message label for the same priority */
    if (message_labels[msg.priority] != NULL) {
        gtk_widget_destroy(message_labels[msg.priority]);
    }

    GtkWidget *label = gtk_label_new(msg.sentence);
    gtk_widget_set_halign(label, GTK_ALIGN_START);  // Horizontal alignment
    gtk_widget_set_valign(label, GTK_ALIGN_START);  // Vertical alignment

    gtk_grid_attach(GTK_GRID(grid), label, 0, msg.priority, 1, 1);

    /* Store the new label for the same priority */
    message_labels[msg.priority] = label;

    gtk_widget_show_all(window);
}

/*
 * GTK is not thread-safe: the widgets are only modified by the main thread.
 * The reading thread hands each message over with g_idle_add(), and this
 * function is then called by the main loop.
 */
gboolean show_message(gpointer data) {
    Message *msg = data;

    display_message(*msg);
    g_free(msg);
    return G_SOURCE_REMOVE; /* called only once */
}

gpointer read_queue(gpointer data) {
    mqd_t mq;
    struct mq_attr attr;
    Message msg;

    (void) data;
    /* The queue is created by message_sender */
    mq = mq_open(QUEUE_NAME, O_RDONLY);
    if (mq == (mqd_t) - 1) {
        perror("mq_open");
        exit(EXIT_FAILURE);
    }

    /* The reception buffer must be at least mq_msgsize bytes long */
    if (mq_getattr(mq, &attr) == -1 || attr.mq_msgsize > (long) sizeof(Message)) {
        fprintf(stderr, "Unexpected message size in %s\n", QUEUE_NAME);
        exit(EXIT_FAILURE);
    }

    while (1) {
        if (mq_receive(mq, (char *) &msg, sizeof(Message), NULL) == -1) {
            perror("mq_receive");
            break;
        }
        msg.sentence[sizeof(msg.sentence) - 1] = '\0'; /* in case */

        Message *copy = g_new(Message, 1);
        *copy = msg;
        g_idle_add(show_message, copy); /* displayed by the main thread */
    }
    mq_close(mq);
    return NULL;
}

int main(int argc, char *argv[]) {
    gtk_init(&argc, &argv);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(window), "Message Queue Consumer");
    gtk_container_set_border_width(GTK_CONTAINER(window), 10);
    g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

    grid = gtk_grid_new();
    gtk_grid_set_row_homogeneous(GTK_GRID(grid), FALSE);
    gtk_container_add(GTK_CONTAINER(window), grid);

    /* Start reading messages from the message queue */
    g_thread_new(NULL, read_queue, NULL);

    gtk_widget_show_all(window);
    gtk_main();

    return 0;
}
posix_messages/src/mq_news_receiver.c

View on GitHub

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

#ifdef __APPLE__
#include "macosx/mqueue.h"
#elif __linux__
#include <mqueue.h>
#endif

/**
 * @file mq_news_receiver.c
 * @brief Receiver (and creator) of the POSIX message queue "/news".
 *
 * Course "Operating Systems", chapter "Files de messages", slide
 * "Exemple - récepteur (créateur)". To be used with mq_news_sender.c.
 *
 * The receiver creates the queue, blocks in mq_receive() while the queue is
 * empty, prints the oldest message of highest priority, then removes the
 * queue: it is the creator and the exchange is over (close != unlink).
 * The reception buffer must be at least mq_msgsize bytes long (EMSGSIZE
 * otherwise), and a message is not a '\0'-terminated string.
 *
 * \code{.bash}
 *   $ ./mq_news_receiver &
 *   $ ./mq_news_sender 10 BBB
 *   [10] BBB
 * \endcode
 */

#define NOM "/news"

int main(void) {
    struct mq_attr attr;
    unsigned int prio;
    mqd_t mq = mq_open(NOM, O_CREAT | O_RDONLY, 0600, NULL);
    if (mq == (mqd_t) -1) {
        perror("mq_open");
        return EXIT_FAILURE;
    }
    if (mq_getattr(mq, &attr) == -1) {  /* before malloc */
        perror("mq_getattr");
        mq_close(mq);
        mq_unlink(NOM);
        return EXIT_FAILURE;
    }
    char *buf = malloc(attr.mq_msgsize);
    if (buf == NULL) {
        perror("malloc");
        mq_close(mq);
        mq_unlink(NOM);
        return EXIT_FAILURE;
    }
    ssize_t n = mq_receive(mq, buf, attr.mq_msgsize, &prio);
    if (n != -1)
        printf("[%u] %.*s\n", prio, (int) n, buf);
    else
        perror("mq_receive");
    free(buf);
    mq_close(mq);
    mq_unlink(NOM);      /* creator, exchange over */
    return n == -1 ? EXIT_FAILURE : EXIT_SUCCESS;
}
posix_messages/src/mq_news_sender.c

View on GitHub

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

#ifdef __APPLE__
#include "macosx/mqueue.h"
#elif __linux__
#include <mqueue.h>
#endif

/**
 * @file mq_news_sender.c
 * @brief Sender of one message with a priority to the POSIX queue "/news".
 *
 * Course "Operating Systems", chapter "Files de messages", slide
 * "Exemple - émetteur". To be used with mq_news_receiver.c.
 *
 * The sender opens the existing queue (created by the receiver) in write
 * only mode, deposits one message with the given priority and closes the
 * queue. It does not call mq_unlink(): only the creator removes the queue.
 *
 * \code{.bash}
 *   $ ./mq_news_receiver &
 *   $ ./mq_news_sender 10 BBB
 *   [10] BBB
 * \endcode
 */

#define NOM "/news"      /* created by the receiver */

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "usage : %s prio msg\n", argv[0]);
        return EXIT_FAILURE;
    }
    mqd_t mq = mq_open(NOM, O_WRONLY);
    if (mq == (mqd_t) -1) {
        perror("mq_open");
        return EXIT_FAILURE;
    }
    /* strtoul: string -> unsigned integer */
    unsigned int prio = (unsigned int) strtoul(argv[1], NULL, 10);
    int r = mq_send(mq, argv[2], strlen(argv[2]), prio);
    if (r == -1)
        perror("mq_send");
    mq_close(mq);        /* no mq_unlink here */
    return r == -1 ? EXIT_FAILURE : EXIT_SUCCESS;
}
posix_messages/src/posix_msg_receiver.c

View on GitHub

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

#ifdef __APPLE__
#include "macosx/mqueue.h"
#elif __linux__
#include <mqueue.h>
#endif

/**
 * @file posix_msg_receiver.c
 *
 * @brief A Receiver application using POSIX mqueue
 */

int main(int argc, char *argv[]) {
    int size;
    int nb_messages;
    long int duration;
    long int max_duration;
    long int min_duration;
    long int sum_durations;
    mqd_t mq;
    char *buffer;
    struct mq_attr attr;
    struct timeval hour;
    struct timeval *received_hour;

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

    mq = mq_open(argv[1], O_RDONLY, 0600, NULL);
    if (mq == (mqd_t) - 1) {
        perror(argv[1]);
        exit(EXIT_FAILURE);
    }

    if (mq_getattr(mq, &attr) != 0) {
        perror("Unable to get attributes from the message queue.");
        exit(EXIT_FAILURE);
    }

    size = attr.mq_msgsize;
    buffer = (char *) malloc(size);
    if (buffer == NULL) {
        perror("Unable to allocate memory for the buffer");
        exit(EXIT_FAILURE);
    }

    received_hour = (struct timeval *) buffer;

    while (1) {
        nb_messages = 0;
        max_duration = 0;
        min_duration = LONG_MAX;  /* Use LONG_MAX from limits.h */
        sum_durations = 0;

        long start_time, current_time;
        gettimeofday(&hour, NULL);
        start_time = hour.tv_sec * 1000000L + hour.tv_usec;

        do {
            if (mq_receive(mq, buffer, size, NULL) == -1) {
                perror("mq_receive"); /* otherwise the buffer is not a date */
                exit(EXIT_FAILURE);
            }

            gettimeofday(&hour, NULL);
            current_time = hour.tv_sec * 1000000L + hour.tv_usec;
            duration = current_time - (received_hour->tv_sec * 1000000L + received_hour->tv_usec);

            /* Update min and max durations */
            if (duration > max_duration) max_duration = duration;
            if (duration < min_duration) min_duration = duration;
            sum_durations += duration;

            nb_messages++;
        } while (current_time - start_time < 1000000L); /* 1 second in microseconds */

        fprintf(stdout, "min = %3ld max = %3ld moy= %5.1f\n",
                min_duration, max_duration, ((float) sum_durations) / nb_messages);
    }
}
posix_messages/src/posix_msg_sender.c

View on GitHub

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

#ifdef __APPLE__
#include "macosx/mqueue.h"
#elif __linux__
#include <mqueue.h>
#endif

/**
 * @file posix_msg_sender.c
 *
 * @brief A sender application using POSIX mqueue.
 */

volatile sig_atomic_t keep_running = 1;

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

int main(int argc, char *argv[]) {
    mqd_t mq;
    struct timeval hour;
    struct sigaction action;

    /* Initialize the structure to zero before use. */
    memset(&action, '\0', sizeof(action));

    /* Set the new handler */
    action.sa_handler = &handle_sigint;
    sigemptyset(&action.sa_mask);

    /* Install the new handler of the SIGINT signal */
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

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

    mq = mq_open(argv[1], O_WRONLY | O_CREAT, 0600, NULL);
    if (mq == (mqd_t) - 1) {
        perror(argv[1]);
        exit(EXIT_FAILURE);
    }

    while (keep_running) {
        gettimeofday(&hour, NULL);
        if (mq_send(mq, (char *) &hour, sizeof(hour), 1) == -1) {
            perror("mq_send");
            break;
        }
    }

    mq_close(mq);
    mq_unlink(argv[1]); /* the sender created the queue: it removes it */

    return EXIT_SUCCESS;
}
shared_memory/src/color_displayer.c

View on GitHub

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

/**
 * @file color_displayer.c
 *
 * This program displays color data from a shared memory segment using GTK+ 3.
 * It continuously updates the displayed colors based on the shared memory content.
 *
 * No synchronization: the reader may see data that is only partly updated. See the course, chapter "Synchronisation".
 */

typedef struct {
    int *ptr;        /*<! Pointer to the shared memory segment */
    int matrix_size; /*<! Size of the color matrix */
} SharedData;

/** 
 * Redraws window every 500 ms.
 */
gboolean timeout_callback(gpointer data) {
    GtkWidget *darea = (GtkWidget *) data;
    gtk_widget_queue_draw(darea);
    return TRUE; /* Continue calling this function */
}

/**
 * Handles the 'draw' event to render the color data.
 */
gboolean on_draw_event(GtkWidget *widget, cairo_t *cr, gpointer user_data) {
    SharedData *data;
    int i;
    int j;
    double red;
    double green;
    double blue;

    (void) widget;
    data = (SharedData *) user_data;
    for (i = 0; i < data->matrix_size; i++) {
        for (j = 0; j < data->matrix_size; j++) {
            red = data->ptr[(i * data->matrix_size + j) * 3] / 255.0;
            green = data->ptr[(i * data->matrix_size + j) * 3 + 1] / 255.0;
            blue = data->ptr[(i * data->matrix_size + j) * 3 + 2] / 255.0;
            cairo_set_source_rgb(cr, red, green, blue);
            cairo_rectangle(cr, j, i, 1, 1);
            cairo_fill(cr);
        }
    }
    return FALSE; /* Event propagation stops here */
}

int main(int argc, char *argv[]) {
    int shm_fd;
    GtkWidget *window;
    GtkWidget *darea;
    SharedData data;

    gtk_init(&argc, &argv);

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <matrix_size>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    data.matrix_size = atoi(argv[1]);
    shm_fd = shm_open("/matrix", O_RDONLY, 0);
    if (shm_fd == -1) {
        perror("shm_open");
        return EXIT_FAILURE;
    }

    data.ptr = mmap(0, data.matrix_size * data.matrix_size * 3 * sizeof(int),
                    PROT_READ, MAP_SHARED, shm_fd, 0);
    if (data.ptr == MAP_FAILED) {
        perror("mmap");
        close(shm_fd);
        return EXIT_FAILURE;
    }

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
    gtk_window_set_default_size(GTK_WINDOW(window), data.matrix_size, data.matrix_size);
    gtk_window_set_title(GTK_WINDOW(window), "POSIX Shared Memory Color Display");

    darea = gtk_drawing_area_new();
    gtk_container_add(GTK_CONTAINER(window), darea);

    g_timeout_add(500, timeout_callback, darea);
    g_signal_connect(G_OBJECT(darea), "draw", G_CALLBACK(on_draw_event), &data);
    g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);

    gtk_widget_show_all(window);
    gtk_main();

    if (munmap(data.ptr, data.matrix_size * data.matrix_size * 3 * sizeof(int)) == -1) {
        perror("munmap");
    }
    close(shm_fd);

    return EXIT_SUCCESS;
}
shared_memory/src/color_modifier.c

View on GitHub

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

/**
 * @file color_modifier.c
 * @brief A program that modifies color data in shared memory.
 *
 * This program fills a matrix in shared memory with random color values.
 * The matrix size is passed as a command-line argument. The program
 * uses POSIX shared memory and updates the colors at regular intervals.
 *
 * No synchronization: the reader may see data that is only partly updated. See the course, chapter "Synchronisation".
 */

#define MAX_MATRIX_SIZE 800

volatile sig_atomic_t keep_running = 1;

/**
 * Signal handler for SIGINT (Ctrl-C).
 *
 * @param sig Signal number.
 */
void handle_sigint(int sig) {
    (void) sig;
    keep_running = 0;
}

int main(int argc, char *argv[]) {
    int shm_fd;
    int *ptr;
    int i, j;
    int MATRIX_SIZE;
    struct sigaction action;

    /* Check if matrix size is passed as an argument */
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <size_of_the_shared_memory>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /* Convert the argument to an integer */
    MATRIX_SIZE = atoi(argv[1]);
    if (MATRIX_SIZE <= 0 || MATRIX_SIZE > MAX_MATRIX_SIZE) {
        fprintf(stderr, "Matrix size should be between 1 and %d\n", MAX_MATRIX_SIZE);
        exit(EXIT_FAILURE);
    }

    shm_unlink("/matrix");

    /* Set up the structure for signal handling */
    memset(&action, '\0', sizeof(action));
    action.sa_handler = &handle_sigint;
    sigemptyset(&action.sa_mask);
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    /* Open a shared memory segment */
    shm_fd = shm_open("/matrix", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    if (shm_fd == -1) {
        perror("shm_open");
        exit(EXIT_FAILURE);
    }

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

    /* Map the shared memory segment into the address space */
    ptr = mmap(0, MATRIX_SIZE * MATRIX_SIZE * 3 * sizeof(int), PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (ptr == MAP_FAILED) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }

    struct timespec delay = { 0, 500000000L }; /* 500 ms */

    /* Initialize the random number generator */
    srand(time(NULL));

    /* Main loop to fill the matrix with random color values */
    while (keep_running) {
        for (i = 0; i < MATRIX_SIZE; i++) {
            for (j = 0; j < MATRIX_SIZE; j++) {
                ptr[(i * MATRIX_SIZE + j) * 3] = rand() % 256; /* Red */
                ptr[(i * MATRIX_SIZE + j) * 3 + 1] = rand() % 256; /* Green */
                ptr[(i * MATRIX_SIZE + j) * 3 + 2] = rand() % 256; /* Blue */
            }
        }
        nanosleep(&delay, NULL); /* Wait for 500 ms (usleep() is no longer POSIX) */
    }

    /* Detach the shared memory segment */
    if (munmap(ptr, MATRIX_SIZE * MATRIX_SIZE * 3 * sizeof(int)) == -1) {
        perror("munmap");
        exit(EXIT_FAILURE);
    }

    /* Close the shared memory file descriptor */
    close(shm_fd);
    shm_unlink("/matrix");

    return EXIT_SUCCESS;
}
shared_memory/src/mmap_buffer_01.c

View on GitHub

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

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>
#include <sys/mman.h>

/**
 * @file mmap_buffer_01.c
 *
 * Producer-consumer program using a shared memory that stores a single integer.
 * WARNING: sleep() is NOT a synchronization mechanism; values may be missed
 * or read twice. See mmap_buffer_03.c for a version using semaphores.
 * This code is based on the example proposed by:  Janet Davis (2006) and Henry
 * Walker (2004).
 *
 * @author Alain Lebret (2011)
 * @author Janet Davis (2006)
 * @author Henry Walker (2004)
 * @version 1.3
 * @date 2011-12-01
 */

#define INTEGER_SIZE sizeof(int)
#define ITERATIONS 10

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

/**
 * Writes the square of a number onto the shared memory.
 */
void write_memory(void *shared_memory) {
    int i;

    for (i = 0; i < ITERATIONS; i++) {
        *((int *) shared_memory) = i * i;

        printf("Parent: i = %2d, value written = %2d (i * i)\n", i, i * i);
        sleep(1);  /* wait 1 sec. to allow his child to read the value */
    }
}

/**
 * Manages the parent process. It writes data to the shared memory and waits
 * for his child to finish.
 */
void manage_parent(void *shared_memory) {
    pid_t child;
    int status;

    printf("Parent process (PID %ld)\n", (long) getpid());
    write_memory(shared_memory);

    child = wait(&status);
    if (WIFEXITED(status)) {
        printf("Parent: child %ld has finished (code %d)\n", (long) child,
               WEXITSTATUS(status));
    }
}

/**
 * Reads integers from the shared memory and displays them.
 */
void read_memory(void *shared_memory) {
    int i;
    int value;

    for (i = 0; i < ITERATIONS; i++) {
        sleep(1);  /* waiting for the memory update (not as good as semaphore) */
        value = *((int *) shared_memory);
        printf("Child: read value = %2d\n", value);
    }
}

/**
 * Manages the child process that reads all data from shared memory.
 */
void manage_child(void *shared_memory) {
    printf("Child process (PID %ld)\n", (long) getpid());
    read_memory(shared_memory);
    printf("Child: memory has been consumed.\n");
}

/**
 * Creates and initializes a new shared memory using the mmap primitive.
 * @return Pointer on the shared memory
 */
void *create_shared_memory(void) {
    /* initialize shared memory using mmap */
    void *shared_memory = mmap(0, /* beginning (starting address is ignored) */
                               INTEGER_SIZE, /* size of the shared memory */
                               PROT_READ | PROT_WRITE, /* protection */
                               MAP_SHARED | MAP_ANONYMOUS,
                               -1, /* the shared memory do not use a file */
                               0);  /* ignored: only set when using a file */

    if (shared_memory == MAP_FAILED) {
        handle_fatal_error("Error [mmap()]");
    }
    return shared_memory;
}

int main(void) {
    pid_t pid;
    void *shared_memory;

    shared_memory = create_shared_memory();

    pid = fork();
    if (pid == -1) {
        handle_fatal_error("Error [fork()]");
    }
    if (pid > 0) {
        manage_parent(shared_memory);
        /* Cleanup in parent process */
        if (munmap(shared_memory, INTEGER_SIZE) == -1) {
            perror("munmap");
        }
    } else {
        manage_child(shared_memory);
        /* Cleanup in child process */
        if (munmap(shared_memory, INTEGER_SIZE) == -1) {
            perror("munmap");
        }
    }

    return EXIT_SUCCESS;
}
shared_memory/src/mmap_buffer_02.c

View on GitHub

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

/**
 * @file mmap_buffer_02.c
 *
 * Producer-consumer program using a shared memory that stores a buffer of
 * integers. The busy waiting on shared indices only illustrates the problem
 * (volatile prevents the compiler from caching them, but it is neither
 * atomic nor efficient): see mmap_buffer_03.c for semaphores.
 * This code is based on the example presented by:  Janet Davis (2006)
 * and Henry Walker (2004).
 *
 * @author Alain Lebret (2011)
 * @author Janet Davis (2006)
 * @author Henry Walker (2004)
 * @version 1.3
 * @date 2011-12-01
 */

#define INTEGER_SIZE sizeof(int)
#define BUFFER_SIZE 5
#define MEMORY_SIZE (BUFFER_SIZE+2)*INTEGER_SIZE
#define ITERATIONS 10

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

/**
 * Writes the square of a series of integers onto the shared memory.
 * This function implements a simple busy-waiting mechanism to ensure
 * synchronization between producer and consumer.
 */
void write_memory(volatile int *buffer, volatile int *begin, volatile int *end) {
    int i;

    for (i = 0; i < ITERATIONS; i++) {
        while ((*begin + 1) % BUFFER_SIZE == *end) {}

        buffer[*begin] = i * i;
        *begin = (*begin + 1) % BUFFER_SIZE;

        printf("Parent: initial value %2d before writing in the buffer\n", i);
    }
}

/**
 * Manages the parent process. It writes data to the shared memory and waits
 * for his child to finish.
 */
void manage_parent(volatile int *buffer, volatile int *begin, volatile int *end) {
    pid_t child;
    int status;

    printf("Parent process (PID %ld)\n", (long) getpid());
    write_memory(buffer, begin, end);
    printf("Parent: end of production.\n");

    child = wait(&status);
    if (WIFEXITED(status)) {
        printf("Parent: child %ld has finished (code %d)\n", (long) child,
               WEXITSTATUS(status));
    }
}

/**
 * Reads a series of integers from the shared memory and displays them.
 * This function implements a simple busy-waiting mechanism for synchronization.
 */
void read_memory(volatile int *buffer, volatile int *in, volatile int *out) {
    int i;
    int value;

    for (i = 0; i < ITERATIONS; i++) {
        sleep(1);  /* slows the reader down, so that the buffer fills up */

        while (*in == *out) {}  /* active wait: buffer empty (a semaphore avoids this) */

        value = buffer[*out];
        *out = (*out + 1) % BUFFER_SIZE;
        printf("Child: element %2d == %2d read from the buffer.\n", i, value);
    }
}

/**
 * Manages the child process that reads all data from shared memory.
 */
void manage_child(volatile int *buffer, volatile int *in, volatile int *out) {
    printf("Child process (PID %ld)\n", (long) getpid());
    read_memory(buffer, in, out);
    printf("Child: memory has been consumed.\n");
}

/**
 * Creates and initializes a new shared memory using mmap.
 * @return Pointer on the shared memory
 */
void *create_shared_memory(void) {
    /* initialize shared memory using mmap */
    void *shared_memory = mmap(0, /* beginning (starting address is ignored) */
                               MEMORY_SIZE, /* size of the shared memory */
                               PROT_READ | PROT_WRITE, /* protection */
                               MAP_SHARED | MAP_ANONYMOUS,
                               -1, /* the shared memory do not use a file */
                               0);  /* ignored: set when using a file */

    if (shared_memory == MAP_FAILED) {
        handle_fatal_error("Error allocating shared memory using mmap");
    }
    return shared_memory;
}

int main(void) {
    pid_t pid;
    volatile int *buffer; /* logical base address for buffer */
    volatile int *in;     /* pointer to logical 'in' address for producer */
    volatile int *out;    /* pointer to logical 'out' address for consumer */
    void *shared_memory; /* shared memory base address */

    shared_memory = create_shared_memory();

    /* The segment of shared memory is organised as:
     *  0                                                n-1   n   n+1
     * ----------------------------------------------------------------
     * |                                                    |    |    |
     * ----------------------------------------------------------------
     *  ^                                                    ^    ^
     *  buffer                                               in   out
     */

    buffer = (volatile int *) shared_memory;
    in = buffer + BUFFER_SIZE;       /* pointer arithmetic counts in ints, */
    out = buffer + BUFFER_SIZE + 1;  /* not in bytes */

    *in = *out = 0;          /* starting index */

    pid = fork();
    if (pid == -1) {
        handle_fatal_error("Error [fork()]");
    }
    if (pid == 0) {
        manage_child(buffer, in, out);
        /* Child process cleanup */
        if (munmap(shared_memory, MEMORY_SIZE) == -1) {
            perror("munmap");
        }
    } else {
        manage_parent(buffer, in, out);
        /* Parent process cleanup */
        if (munmap(shared_memory, MEMORY_SIZE) == -1) {
            perror("munmap");
        }
    }

    return EXIT_SUCCESS;
}
shared_memory/src/mmap_buffer_03.c

View on GitHub

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

/**
 * @file mmap_buffer_03.c
 *
 * Producer-consumer program using a shared memory that stores a buffer of
 * integers and synchronized using semaphores. This code is based on the example
 * presented by:  Janet Davis (2006) and Henry Walker (2004).
 *
 * @author Alain Lebret (2011)
 * @author Janet Davis (2006)
 * @author Henry Walker (2004)
 * @version 1.3
 * @date 2011-12-01
 */

#define INTEGER_SIZE sizeof(int)
#define BUFFER_SIZE 5
#define MEMORY_SIZE (BUFFER_SIZE+2)*INTEGER_SIZE
#define ITERATIONS 10

#define BUFFER_USED  0
#define BUFFER_SPACE 1
#define NBR_SEMAPHORES  2

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

/**
 * Creates and initializes a group of two semaphores.
 * @return Identifier of the group of semaphores
 */
int initialize_semaphores(void) {
    int semid;

    /* permission 0600 = lecture/modification by user */
    if ((semid = semget(IPC_PRIVATE, NBR_SEMAPHORES, IPC_CREAT | 0600))
        < 0) {
        handle_fatal_error("Error [semget()]");
    }

    /* 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(semid, BUFFER_SPACE, SETVAL, BUFFER_SIZE) < 0) {
        handle_fatal_error("Error first [semctrl()]");
    }

    if (semctl(semid, BUFFER_USED, SETVAL, 0) < 0) {
        handle_fatal_error("Error second [semctrl()]");
    }

    return semid;
}

/**
 * Performs a P() operation ("wait") on a System V semaphore.
 * Not named sem_wait(): that name belongs to POSIX semaphores (<semaphore.h>).
 * @param semid Identifier of the group of two semaphores.
 * @param index Index of the semaphore in the group.
 */
void P(int semid, int index) {
    struct sembuf sops[1];

    sops[0].sem_num = index;
    sops[0].sem_op = -1;
    sops[0].sem_flg = 0;

    if (semop(semid, sops, 1) < 0) {
        handle_fatal_error("Error using P()");
    }
}

/**
 * Performs a V() operation ("signal") on a semaphore.
 * @param semid Identifier of the group of two semaphores.
 * @param index Index of the semaphore in the group.
 */
void V(int semid, int index) {
    struct sembuf sops[1];

    sops[0].sem_num = index;
    sops[0].sem_op = 1;
    sops[0].sem_flg = 0;

    if (semop(semid, sops, 1) < 0) {
        handle_fatal_error("Error using V()");
    }
}

/**
 * Writes the square of a serie of integers onto the shared memory.
 */
void write_memory(int *buffer, int *in, int *out, int semid) {
    int i;

    (void) out;  /* only used by the consumer */
    for (i = 0; i < ITERATIONS; i++) {
        P(semid, BUFFER_SPACE);  /* P() -- wait */

        buffer[*in] = i * i;
        *in = (*in + 1) % BUFFER_SIZE;
        printf("Parent: initial value %2d before writing in the buffer\n", i);

        V(semid, BUFFER_USED); /* V() -- signal */

        if ((i % 4) == 0) {
            sleep(1); /* slow production */
        }
    }
}

/**
 * Manages the parent process. It writes data to the shared memory and waits
 * for his child to finish.
 */
void manage_parent(int *buffer, int *in, int *out, int semid) {
    pid_t child;
    int status;

    printf("Parent process (PID %ld)\n", (long) getpid());
    write_memory(buffer, in, out, semid);
    printf("Parent: end of production.\n");

    child = wait(&status);
    if (WIFEXITED(status)) {
        printf("Parent: child %ld has finished (code %d)\n", (long) child,
               WEXITSTATUS(status));
    }
}

/**
 * Reads a serie of integers from the shared memory and displays them.
 */
void read_memory(int *buffer, int *in, int *out, int semid) {
    int i;
    int value;

    (void) in;  /* only used by the producer */
    for (i = 0; i < ITERATIONS; i++) {
        P(semid, BUFFER_USED);  /* P() -- wait */

        value = buffer[*out];
        *out = (*out + 1) % BUFFER_SIZE;
        printf("Child: element %2d == %2d read from the buffer.\n", i, value);

        V(semid, BUFFER_SPACE); /* V() -- signal */

        if ((i % 3) == 1) {
            sleep(1); /* slow consuming */
        }
    }
}

/**
 * Manages the child process that reads all data from shared memory.
 */
void manage_child(int *buffer, int *in, int *out, int semid) {
    printf("Child process (PID %ld)\n", (long) getpid());
    read_memory(buffer, in, out, semid);
    printf("Child: memory has been totally consumed.\n");
}

/**
 * Creates and initializes a new shared memory using mmap.
 * @return Pointer on the shared memory
 */
void *create_shared_memory(void) {
    /* initialize shared memory using mmap */
    void *shared_memory = mmap(0, /* beginning (starting address is ignored) */
                               MEMORY_SIZE, /* size of the shared memory */
                               PROT_READ | PROT_WRITE, /* protection */
                               MAP_SHARED | MAP_ANONYMOUS,
                               -1, /* the shared memory do not use a file */
                               0);  /* ignored: set when using a file */

    if (shared_memory == MAP_FAILED) {
        handle_fatal_error("Error [mmap()]");
    }
    return shared_memory;
}

int main(void) {
    pid_t pid;

    void *shared_memory; /* shared memory base address */
    int *buffer; /* logical base address for buffer */
    int *in; /* pointer to logical 'in' address for producer */
    int *out; /* pointer to logical 'out' address for consumer */
    int semaphores; /* identifier for a semaphore set */

    shared_memory = create_shared_memory();

    /* The segment of shared memory is organised as:
     *  0                                                n-1   n   n+1
     * ----------------------------------------------------------------
     * |                                                    |    |    |
     * ----------------------------------------------------------------
     *  ^                                                    ^    ^
     *  buffer                                               in   out
     */

    buffer = (int *) shared_memory;
    in = buffer + BUFFER_SIZE;       /* pointer arithmetic counts in ints, */
    out = buffer + BUFFER_SIZE + 1;  /* not in bytes */

    *in = *out = 0;          /* starting index */

    semaphores = initialize_semaphores();

    pid = fork();
    if (pid == -1) {
        handle_fatal_error("Error [fork()]");
    }
    if (pid == 0) {
        manage_child(buffer, in, out, semaphores);
    } else {
        manage_parent(buffer, in, out, semaphores); /* waits for the child */

        if (semctl(semaphores, 0, IPC_RMID) < 0) {
            handle_fatal_error("Error when trying to remove semaphores");
        }
        printf("Semaphores have been removed.\n");
    }

    return EXIT_SUCCESS;
}
shared_memory/src/mmap_buffer_04.c

View on GitHub

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

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h> /* wait() */
#include <sys/mman.h>
#include <sys/ipc.h>
#include <sys/sem.h>

/**
 * @file mmap_buffer_04.c
 *
 * Multi-producer-multi-consumer program using a shared memory and synchronized
 * with semaphores. This code is based on the example presented by:  Janet Davis
 * (2006) and Henry Walker (2004).
 *
 * @author Alain Lebret (2011)
 * @author Janet Davis (2006)
 * @author Henry Walker (2004)
 * @version 1.3
 * @date 2011-12-01
 */

#define NBR_CONSUMERS 5  /* number of consumer processes to be spawned */
#define NBR_PRODUCERS 6  /* number of producer processes to be spawned */

#define INTEGER_SIZE sizeof(int)
#define BUFFER_SIZE 5
#define MEMORY_SIZE (BUFFER_SIZE+2)*INTEGER_SIZE

#define ITERATIONS_CONSUMER 12  /* number of iterations for consumer in test run */
#define ITERATIONS_PRODUCER 10  /* number of iterations for producer in test run */

#define BUFFER_USED 0     /* semaphore array index to check buffer elts used */
#define BUFFER_SPACE 1    /* semaphore array index to check buffer elts empty */
#define MUTEX 2        /* semaphore index for mutual exclusion to buffer*/
#define NBR_SEMAPHORES 3     /* number of semaphores */

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

/**
 * Creates a set of semaphores.
 * @param nbr_semaphores The number of semaphores to create.
 * @return Identifier of the set of semaphores
 */
int create_semaphores(int nbr_semaphores) {
    int semid;

    /* permission 0600 = lecture/modification by user */
    if ((semid = semget(IPC_PRIVATE, nbr_semaphores, IPC_CREAT | 0600))
        < 0) {
        handle_fatal_error("Error when creating semaphores");
    }

    return semid;
}

/**
 * Initializes a specific semaphore.
 */
void initialize_semaphore(int semid, int index, int valeur) {
    /* 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(semid, index, SETVAL, valeur) < 0) {
        handle_fatal_error("Error when initializing semaphore");
    }
}

/**
 * Performs a P() operation ("wait") on a System V semaphore.
 * Not named sem_wait(): that name belongs to POSIX semaphores (<semaphore.h>).
 * @param semid Identifier of the group of semaphores.
 * @param index Index of the semaphore in the group.
 */
void P(int semid, int index) {
    struct sembuf sops[1];

    sops[0].sem_num = index;
    sops[0].sem_op = -1;
    sops[0].sem_flg = 0;

    if (semop(semid, sops, 1) < 0) {
        handle_fatal_error("Error using P()");
    }
}

/**
 * Performs a V() operation ("signal") on a semaphore.
 * @param semid Identifier of the group of semaphores.
 * @param index Index of the semaphore in the group.
 */
void V(int semid, int index) {
    struct sembuf sops[1];

    sops[0].sem_num = index;
    sops[0].sem_op = 1;
    sops[0].sem_flg = 0;

    if (semop(semid, sops, 1) < 0) {
        handle_fatal_error("Error using V()");
    }
}

/**
 * Writes the square of a serie of integers onto the shared memory.
 */
void write_memory(int id, int *buffer, int *in, int *out, int semid) {
    int value;
    int i;

    (void) out;  /* only used by the consumers */
    for (i = 0; i < ITERATIONS_PRODUCER; i++) {
        value = 100 * id + i;
        P(semid, BUFFER_SPACE);  /* P() -- wait */
        P(semid, MUTEX);    /* Waiting to access buffer */
        buffer[*in] = value;
        *in = (*in + 1) % BUFFER_SIZE;
        V(semid, MUTEX);  /* End of access */
        V(semid, BUFFER_USED);  /* V() -- signal */
    }
}

/**
 * Writes data to the shared memory.
 */
void produce(int id, int *buffer, int *in, int *out, int semid) {
    printf("Producer of ID %d begins.\n", id);
    write_memory(id, buffer, in, out, semid);
    printf("Producer of ID %d has finished.\n", id);
}

/**
 * Reads and reports values from shared memory buffer.
 */
void consume(int id, int *buffer, int *in, int *out, int semid) {
    int i;
    int value;

    (void) in;  /* only used by the producers */
    printf("Consumer of ID %d begins.\n", id);

    for (i = 0; i < ITERATIONS_CONSUMER; i++) {
        P(semid, BUFFER_USED);  /* wait semaphore for something used */
        P(semid, MUTEX);     /* wait semaphore for buffer access */
        value = buffer[*out];  /* take data from buffer */
        *out = (*out + 1) % BUFFER_SIZE;
        V(semid, MUTEX);     /* signal semaphore for buffer access */
        V(semid, BUFFER_SPACE); /* signal semaphore for space available */

        printf("Consumer of ID %d : element %2d == %2d\n", id, i, value);

        if ((i + id) % 5 == 0) /* pause somewhere in processing */
            sleep(1);               /* to make output more interesting */
    }
    printf("Consumer of ID %d has finished.\n", id);
}

/**
 * Creates and initializes a new shared memory using mmap.
 * @return Pointer on the shared memory
 */
void *create_shared_memory(void) {
    /* initialize shared memory using mmap */
    void *shared_memory = mmap(0, /* beginning (starting address is ignored) */
                               MEMORY_SIZE, /* size of the shared memory */
                               PROT_READ | PROT_WRITE, /* protection */
                               MAP_SHARED | MAP_ANONYMOUS,
                               -1, /* the shared memory do not use a file */
                               0);  /* ignored: set when using a file */

    if (shared_memory == MAP_FAILED) {
        handle_fatal_error("Error allocating shared memory using mmap");
    }
    return shared_memory;
}

int main(void) {
    pid_t pid;
    int i;
    int semid; /* identifier for a semaphore set */
    void *shared_memory; /* shared memory base address */
    int *buffer; /* logical base address for buffer */
    int *in; /* pointer to logical 'in' address for producer */
    int *out; /* pointer to logical 'out' address for consumer */


    shared_memory = create_shared_memory();

    /* The segment of shared memory is organised as:
     *  0                                                n-1   n   n+1
     * ----------------------------------------------------------------
     * |                                                    |    |    |
     * ----------------------------------------------------------------
     *  ^                                                    ^    ^
     *  buffer                                               in   out
     */

    buffer = (int *) shared_memory;
    in = buffer + BUFFER_SIZE;       /* pointer arithmetic counts in ints, */
    out = buffer + BUFFER_SIZE + 1;  /* not in bytes */

    *in = *out = 0;          /* starting index */

    /* Creation and initialization of semaphores */
    semid = create_semaphores(NBR_SEMAPHORES);
    initialize_semaphore(semid, BUFFER_USED, 0);
    initialize_semaphore(semid, BUFFER_SPACE, BUFFER_SIZE);
    initialize_semaphore(semid, MUTEX, 1);

    /* Creation of producers */
    for (i = 1; i <= NBR_PRODUCERS; i++) {
        pid = fork();
        if (pid == -1) {
            handle_fatal_error("Error when trying to fork producers");
        }
        if (pid == 0) {
            produce(i, buffer, in, out, semid);
            exit(EXIT_SUCCESS);
        }
    }

    /* Creation of consumers */
    for (i = 1; i <= NBR_CONSUMERS; i++) {
        pid = fork();
        if (pid == -1) {
            handle_fatal_error("Error when trying to fork consumers");
        }

        if (pid == 0) {
            consume(i, buffer, in, out, semid);
            exit(EXIT_SUCCESS);
        }
    }

    /* Waiting for the end of all consumers */
    printf("All producers and consumers are working...\n");
    printf("Parent process is waiting for them to end...\n");

    /* Waiting for all child processes to complete */
    for (i = 0; i < NBR_PRODUCERS + NBR_CONSUMERS; i++) {
        wait(NULL);
    }

    /* Cleanup: Unmap shared memory */
    if (munmap(shared_memory, MEMORY_SIZE) == -1) {
        perror("munmap");
        /* Handle error */
    }

    /* Remove the semaphore from the system and destroy the set of
     *  semaphores and data structure associated with it. */
    if (semctl(semid, 0, IPC_RMID) < 0) {
        handle_fatal_error("Error removing semaphores");
    }
    printf("Semaphores removed.\n");

    return EXIT_SUCCESS;
}
shared_memory/src/posix_shm_client.c

View on GitHub

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

/**
 * @file posix_shm_client.c
 *
 * Example using a server and a client sharing memory.
 * The client only opens the segment created and sized by the server
 * (neither O_CREAT nor ftruncate()); the server removes it (shm_unlink()).
 * Link with \c -lrt under Linux.
 *
 * No synchronization: the reader may see a value and a result coming from two
 * different updates. See the course, chapter "Synchronisation".
 */

#define MEMORY_PATH "/shm_name"

/**
 * Structure to store a value and its square root.
 */
struct memory_t {
    int value;
    double square_root;
};

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

static volatile sig_atomic_t stop_requested = 0;

/**
 * Requests the end of the main loop when receiving the SIGINT signal.
 */
void handle_sigint(int signum) {
    (void) signum;
    stop_requested = 1;
}

/**
 * Checks if new data is available in the shared memory.
 *
 * @param memory The shared memory segment.
 * @param last_read The last read data from the shared memory.
 * @return 1 if new data is available, 0 otherwise.
 */
int check_for_new_data(struct memory_t *memory, struct memory_t *last_read) {
    /* Check if the current data is different from the last read data */
    if (memory->value != last_read->value ||
        memory->square_root != last_read->square_root) {
        /* Update last_read to the current data */
        last_read->value = memory->value;
        last_read->square_root = memory->square_root;
        return 1; /* New data is available */
    }
    return 0; /* No new data */
}

int main(void) {
    int memory_descriptor;
    size_t memory_size;
    struct memory_t *memory;
    struct memory_t last_read = {0, 0};
    struct sigaction action;

    memory_size = (1 * sizeof(struct memory_t));
    action.sa_handler = &handle_sigint;
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    memory_descriptor = shm_open(
            MEMORY_PATH,
            O_RDONLY,
            0);
    if (memory_descriptor < 0) {
        handle_error("Error [shm_open()]");
    }

    fprintf(stderr, "Shared memory object %s has been opened\n", MEMORY_PATH);

    /* The server sizes the segment: check it is done (otherwise SIGBUS) */
    struct stat mapstat;
    if (fstat(memory_descriptor, &mapstat) == -1) {
        handle_error("Error [fstat()]");
    }
    if (mapstat.st_size < (off_t) memory_size) {
        fprintf(stderr, "Shared memory not ready yet\n");
        exit(EXIT_FAILURE);
    }

    memory = (struct memory_t *) mmap(
            NULL,
            memory_size,
            PROT_READ,
            MAP_SHARED,
            memory_descriptor,
            0);
    if (memory == MAP_FAILED) {
        handle_error("Error [mmap()]");
    }
    fprintf(stderr, "Shared memory of %zu bytes has been projected\n",
            memory_size);

    while (!stop_requested) {
        printf("Value is %d ... ", memory->value);
        printf("and its square root is %f \n", memory->square_root);
        if (check_for_new_data(memory, &last_read)) {
            printf("New data read from shared memory.\n");
        }
        sleep(3);
    }

    if (munmap(memory, memory_size) == -1) {
        perror("munmap");
    }
    close(memory_descriptor);

    return EXIT_SUCCESS;
}
shared_memory/src/posix_shm_consumer.c

View on GitHub

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

/**
 * @file posix_shm_consumer.c
 *
 * Two unrelated programs sharing memory: the consumer (see
 * posix_shm_creator.c for the other one).
 * Lecture: chapter os-09b "Mémoire partagée" ("Deux programmes - le
 * consommateur").
 *
 * The consumer opens the existing segment "/exemple" read-only (neither
 * O_CREAT nor ftruncate()) and displays its contents.
 * As suggested in the correction of exercise 1, it checks the size of the
 * segment first: reading a segment of 0 byte would raise SIGBUS.
 * Link with \c -lrt under Linux.
 *
 * \code{.bash}
 *   $ ./posix_shm_creator       # terminal 1: writes, then waits
 *   $ ./posix_shm_consumer      # terminal 2
 *   42 bonjour
 * \endcode
 */

#define NOM "/exemple"

struct shared_data { int valeur; char message[64]; };

int main(void) {
    /* neither O_CREAT, nor ftruncate() */
    int fd = shm_open(NOM, O_RDONLY, 0);
    if (fd == -1) {
        perror("shm_open");
        return EXIT_FAILURE;
    }

    struct stat st;
    if (fstat(fd, &st) == -1) {
        perror("fstat");
        return EXIT_FAILURE;
    }
    if (st.st_size < (off_t) sizeof(struct shared_data)) {
        fprintf(stderr, "segment pas encore prêt\n");
        return EXIT_FAILURE;
    }

    struct shared_data *shm = mmap(NULL, sizeof *shm,
                                   PROT_READ,
                                   MAP_SHARED, fd, 0);
    if (shm == MAP_FAILED) {
        perror("mmap");
        return EXIT_FAILURE;
    }
    close(fd);

    printf("%d %s\n", shm->valeur, shm->message);

    munmap(shm, sizeof *shm);
    return EXIT_SUCCESS;
}
shared_memory/src/posix_shm_creator.c

View on GitHub

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

/**
 * @file posix_shm_creator.c
 *
 * Two unrelated programs sharing memory: the creator (see
 * posix_shm_consumer.c for the other one).
 * Lecture: chapter os-09b "Mémoire partagée" ("Deux programmes - le
 * créateur").
 *
 * The creator creates the segment "/exemple", sizes it, writes a value and
 * a message, then waits for the Enter key before freeing the projection
 * and removing the name.
 * Link with \c -lrt under Linux.
 *
 * \code{.bash}
 *   $ ./posix_shm_creator       # terminal 1: writes, then waits
 *   $ ./posix_shm_consumer      # terminal 2
 *   42 bonjour
 * \endcode
 */

#define NOM "/exemple"

struct shared_data { int valeur; char message[64]; };

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

int main(void) {
    int fd = shm_open(NOM, O_CREAT | O_RDWR, 0600);
    if (fd == -1) {
        handle_error("Error [shm_open()]");
    }
    /* The creator sizes the segment BEFORE it is used */
    if (ftruncate(fd, sizeof(struct shared_data)) == -1) {
        handle_error("Error [ftruncate()]");
    }
    struct shared_data *shm = mmap(NULL, sizeof *shm,
                                   PROT_READ | PROT_WRITE,
                                   MAP_SHARED, fd, 0);
    if (shm == MAP_FAILED) {
        handle_error("Error [mmap()]");
    }
    close(fd);

    shm->valeur = 42;
    strcpy(shm->message, "bonjour");

    printf("Segment %s ready; press Enter to remove it.\n", NOM);
    getchar();              /* waits for the Enter key */

    munmap(shm, sizeof *shm);
    shm_unlink(NOM);

    return EXIT_SUCCESS;
}
shared_memory/src/posix_shm_fork_wait.c

View on GitHub

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

/**
 * @file posix_shm_fork_wait.c
 *
 * Example 2 of the lecture: a parent and a child sharing an array of 25
 * integers; the child writes, the parent waits for it, then reads.
 * Lecture: chapter os-09b "Mémoire partagée" ("Exemple 2 - un parent et
 * un enfant").
 *
 * The projection is made before fork(): the child inherits it and uses the
 * same physical frames. wait() guarantees that the parent reads after the
 * writing of the child (compare with posix_shm_simple_1.c, which has no
 * synchronization).
 * Link with \c -lrt under Linux.
 *
 * \code{.bash}
 *   $ ./posix_shm_fork_wait
 *   6 3 4 3 0 8 3 6 4 5 1 9 2 7 7 0 5 2 8 1 4 6 9 3 2
 * \endcode
 */

#define N      25           /* 25 integers: 100 bytes */
#define TAILLE (N * sizeof(int))

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

int main(void) {
    int fd = shm_open("/exemple", O_CREAT | O_RDWR, 0644);
    if (fd == -1) {
        handle_error("Error [shm_open()]");
    }
    if (ftruncate(fd, TAILLE) == -1) {
        handle_error("Error [ftruncate()]");
    }
    int *tab = mmap(NULL, TAILLE, PROT_READ | PROT_WRITE,
                    MAP_SHARED, fd, 0);
    if (tab == MAP_FAILED) {
        handle_error("Error [mmap()]");
    }
    close(fd);

    srand(time(NULL));

    pid_t pid = fork();
    if (pid == -1) {
        handle_error("Error [fork()]");
    }
    if (pid == 0) {                   /* child: writes */
        for (int i = 0; i < N; i++) {
            tab[i] = rand() % 10;
        }
        munmap(tab, TAILLE);
        return EXIT_SUCCESS;
    }

    wait(NULL);                       /* parent: waits */
    for (int i = 0; i < N; i++) {
        printf("%d ", tab[i]);
    }
    printf("\n");

    munmap(tab, TAILLE);
    shm_unlink("/exemple");

    return EXIT_SUCCESS;
}
shared_memory/src/posix_shm_ping_pong.c

View on GitHub

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

/**
 * @file posix_shm_ping_pong.c
 *
 * Complete example of the lecture: a parent and a child play ping-pong
 * with a counter placed in a shared memory segment, synchronized by two
 * anonymous POSIX semaphores placed in the segment itself.
 * Lecture: chapter os-09b "Mémoire partagée" ("Exemple complet -
 * ping-pong").
 *
 * The child displays 0, 2, 4 and the parent 1, 3, 5. The semaphores are
 * initialized with pshared = 1, which requires them to be in shared memory.
 *
 * LINUX ONLY: sem_init() is not implemented under macOS (it fails with
 * ENOSYS); there, use named semaphores (sem_open()).
 * Link with \c -lrt -pthread under Linux.
 *
 * \code{.bash}
 *   $ ./posix_shm_ping_pong
 *   enfant : 0
 *   parent : 1
 *   enfant : 2
 *   parent : 3
 *   enfant : 4
 *   parent : 5
 * \endcode
 */

#define NOM "/pingpong"
#define N   3

typedef struct { sem_t enfant, parent; int val; } shm_t;

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

int main(void) {
    int fd = shm_open(NOM, O_CREAT | O_RDWR, 0600);
    if (fd == -1) {
        handle_error("Error [shm_open()]");
    }
    if (ftruncate(fd, sizeof(shm_t)) == -1) {
        handle_error("Error [ftruncate()]");
    }
    shm_t *s = mmap(NULL, sizeof *s,
                    PROT_READ | PROT_WRITE,
                    MAP_SHARED, fd, 0);
    if (s == MAP_FAILED) {
        handle_error("Error [mmap()]");
    }
    close(fd);

    if (sem_init(&s->enfant, 1, 0) == -1 || sem_init(&s->parent, 1, 0) == -1) {
        perror("Error [sem_init()] (not supported on macOS)"); /* before errno changes */
        munmap(s, sizeof *s);
        shm_unlink(NOM);
        exit(EXIT_FAILURE);
    }
    s->val = 0;

    pid_t pid = fork();
    if (pid == -1) {
        handle_error("Error [fork()]");
    }
    if (pid == 0) {                    /* child */
        for (int i = 0; i < N; i++) {
            sem_wait(&s->enfant);
            printf("enfant : %d\n", s->val++);
            fflush(stdout);
            sem_post(&s->parent);
        }
        return EXIT_SUCCESS;
    }
    for (int i = 0; i < N; i++) {      /* parent */
        sem_post(&s->enfant);
        sem_wait(&s->parent);
        printf("parent : %d\n", s->val++);
        fflush(stdout);
    }
    wait(NULL);

    sem_destroy(&s->enfant);
    sem_destroy(&s->parent);
    munmap(s, sizeof *s);
    shm_unlink(NOM);

    return EXIT_SUCCESS;
}
shared_memory/src/posix_shm_server.c

View on GitHub

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

/**
 * @file posix_shm_server.c
 *
 * Example using a server and a client sharing memory.
 * Link with \c -lrt -lm under Linux.
 *
 * No synchronization: the reader may see a value and a result coming from two
 * different updates. See the course, chapter "Synchronisation".
 */

#define MEMORY_PATH "/shm_name"

static volatile sig_atomic_t stop_requested = 0;

/**
* Structure to store a value and its square root.
*/
struct memory_t {
    int value;
    double square_root;
};

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

/**
 * Requests the end of the main loop when receiving the SIGINT signal
 * (the shared memory is then unlinked by main()).
 */
void handle_sigint(int signum) {
    (void) signum;
    stop_requested = 1;
}

int main(void) {
    int memory_descriptor;
    int value;
    size_t memory_size;
    struct memory_t *memory;
    struct sigaction action;

    memory_size = (1 * sizeof(struct memory_t));

    memset(&action, '\0', sizeof(action));
    action.sa_handler = &handle_sigint;
    sigemptyset(&action.sa_mask);
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    memory_descriptor = shm_open(
            MEMORY_PATH,
            O_CREAT | O_RDWR,
            0600);
    if (memory_descriptor < 0) {
        handle_error("Error [shm_open()]");
    }

    fprintf(stderr, "Shared memory object %s has been created\n", MEMORY_PATH);

    if (ftruncate(memory_descriptor, memory_size) == -1) {
        handle_error("Error [ftruncate()]");
    }

    memory = (struct memory_t *) mmap(
            NULL,
            memory_size,
            PROT_READ | PROT_WRITE,
            MAP_SHARED,
            memory_descriptor,
            0);
    if (memory == MAP_FAILED) {
        handle_error("Error [mmap()]");
    }
    fprintf(stderr, "Memory of %zu bytes allocated.\n", memory_size);

    value = 1;

    while (!stop_requested) {
        memory->value = value;
        memory->square_root = sqrt(value);
        fprintf(stderr, "Updated shared memory: value = %d, square root = %f\n",
                memory->value, memory->square_root);
        sleep(5);
        value++;
    }

    if (munmap(memory, memory_size) == -1) {
        perror("munmap");
    }
    if (close(memory_descriptor) == -1) {
        perror("close");
    }
    if (shm_unlink(MEMORY_PATH) == -1) {
        perror("shm_unlink");
        return EXIT_FAILURE;
    }
    fprintf(stderr, "Shared memory %s unlinked successfully.\n", MEMORY_PATH);

    return EXIT_SUCCESS;
}
shared_memory/src/posix_shm_simple_1.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <stdlib.h>
#include <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 posix_shm_simple_1.c
 *
 * Example using parent and child processes sharing memory without synchronization.
 * Link with \c -lrt under Linux.
 *
 * No synchronization on purpose: the child will probably display 0s, read
 * before the parent has written.
 */

#define SHM_SIZE 100

int main(void) {
    int fd;
    int i;
    int *ptr;
    pid_t pid;
    const size_t shm_bytes = SHM_SIZE * sizeof(int);

    srand(time(NULL));

    fd = shm_open("/pipeautique1", O_CREAT | O_RDWR, 0644);
    if (fd == -1) {
        perror("Error [shm_open()]");
        exit(EXIT_FAILURE);
    }

    if (ftruncate(fd, (off_t) shm_bytes) == -1) {
        perror("Error [ftruncate()]");
        exit(EXIT_FAILURE);
    }

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

    pid = fork();
    if (pid == -1) {
        perror("Error [fork()]");
        exit(EXIT_FAILURE);
    }

    if (pid > 0) {
        for (i = 0; i < SHM_SIZE; i++) {
            ptr[i] = rand() % SHM_SIZE;
            printf("%d ", ptr[i]);
        }
        printf("\n");
    } else {
        for (i = 0; i < SHM_SIZE; i++) {
            printf("%d ", ptr[i]);
        }
        printf("\n");
    }
    munmap(ptr, shm_bytes);
    if (pid > 0) {
        wait(NULL);
        shm_unlink("/pipeautique1");
    }

    return EXIT_SUCCESS;
}
shared_memory/src/posix_shm_simple_2.c

View on GitHub

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


/**
 * @file posix_shm_simple_2.c
 *
 * Another example using parent and child processes sharing memory without 
 * synchronization. Link with \c -lrt under Linux.
 *
 * sleep() is not a synchronization: it makes the expected order likely, but
 * does not guarantee it (a loaded machine may run the processes in any order).
 */

#define N 3  /* number of shared integers */

/**
 * Displays content of the specified integer values.
 */
void display(char *prog, int *bytes, int n);

/**
 * Handles a fatal error. It displays a message, then exits.
 */
void handle_error(const char *message);

int main(void) {
    int shm_fd;     /* file descriptor, from shm_open() */
    int *shm_base;  /* base address, from mmap() */
    const char *name = "/pipeautique2"; /* shared memory name */
    const size_t SIZE = N * sizeof(int); /* shared memory size: the integers
                                            themselves, never a pointer */

    /* create the shared memory segment as if it was a file */
    shm_fd = shm_open(name, O_CREAT | O_RDWR, 0644);
    if (shm_fd == -1) {
        handle_error("Error [shm_open()]");
    }

    /* configure the size of the shared memory segment */
    if (ftruncate(shm_fd, SIZE) == -1) {
        handle_error("Error [ftruncate()]");
    }

    /* map the shared memory segment to the address space of the process */
    shm_base = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (shm_base == MAP_FAILED) {
        handle_error("Error [mmap()]");
    }

    pid_t pid = fork();

    if (pid < 0) {
        handle_error("Error [fork()]");
    }
    if (pid > 0) { /* parent process */
        display("prod1", shm_base, N);
        shm_base[0] = 1;
        display("prod1", shm_base, N);
        sleep(1);
        display("prod1", shm_base, N);
        shm_base[1] = 3;
        display("prod1", shm_base, N);
        sleep(1);
        display("prod1", shm_base, N);
        shm_base[2] = 5;
        display("prod1", shm_base, N);
        sleep(1);
    } else { /* child process */
        display("prod2", shm_base, N);
        shm_base[0] = 2;
        display("prod2", shm_base, N);
        sleep(1);
        display("prod2", shm_base, N);
        shm_base[1] = 4;
        display("prod2", shm_base, N);
        sleep(1);
        display("prod2", shm_base, N);
        shm_base[2] = 6;
        display("prod2", shm_base, N);
        sleep(1);
    }

    /* remove the mapped memory segment from the address space of the process */
    if (munmap(shm_base, SIZE) == -1) {
        handle_error("Error [unmap()]: ");
    }

    /* close the shared memory segment as if it was a file */
    if (close(shm_fd) == -1) {
        handle_error("Error prod / close() failed. ");
    }

    if (pid > 0) {
        wait(NULL);
        shm_unlink("/pipeautique2");
    }

    return EXIT_SUCCESS;
}

void handle_error(const char *message) {
    fprintf(stderr, "%s: %s\n", message, strerror(errno));
    exit(EXIT_FAILURE);
}

void display(char *prog, int *values, int n) {
    int i;

    printf("Display: %s\n", prog);
    for (i = 0; i < n; ++i) {
        printf("%d ", values[i]);
    }
    printf("\n");
}
shared_memory/src/posix_shm_simple_3.c

View on GitHub

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

/**
 * @file posix_shm_simple_3.c
 *
 * Another example using parent and child processes sharing a complex structure memory.
 * There is no synchronization: the child may read before the parent writes.
 * Link with \c -lrt under Linux.
 */

/**
 * Handles a fatal error. It displays a message, then exits.
 */
void handle_error(const char *message);

/* Hard-coded page size: the offset given to mmap() must be a multiple of the
 * real page size, so this program fails (EINVAL) where pages are not 4 KiB
 * (e.g. 16 KiB on Apple Silicon). See posix_shm_two_pages.c, which uses
 * sysconf(_SC_PAGESIZE). */
#define PAGESIZE 4096

typedef struct vector {
    float x;
    float y;
    float z;
} vector_t;

typedef struct color {
    unsigned char red;
    unsigned char green;
    unsigned char blue;
} color_t;

typedef struct s1 {
    int id;
    char name[20];
    int age;
    char padding[PAGESIZE - 2 * sizeof(int) - 20 * sizeof(char)];
} s1_t;

typedef struct s2 {
    vector_t vec;
    color_t col;
    char padding[PAGESIZE - sizeof(vector_t) - sizeof(color_t)];
} s2_t;

typedef struct s1_et_s2 {
    s1_t a_s1;
    s2_t a_s2;
} s1_and_s2_t;


int main(void) {
    int shm_fd;
    pid_t pid;
    s1_t *ptr1;
    s2_t *ptr2;

    srand(time(NULL));

    /* create the shared memory segment as if it was a file */
    shm_fd = shm_open("/pipeautique_simple3", O_CREAT | O_RDWR, 0644);
    if (shm_fd == -1) {
        handle_error("Error [shm_open()]");
    }

    if (ftruncate(shm_fd, sizeof(s1_and_s2_t)) == -1) {
        handle_error("Error setting size with ftruncate");
    }

    /* map the shared memory segment for struct s1 to the address space of the process */
    ptr1 = (s1_t *) mmap(NULL, sizeof(s1_t), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (ptr1 == MAP_FAILED) {
        handle_error("Error [mmap() ptr1]");
    }

    /* map the shared memory segment for struct s2 to the address space of the process */
    ptr2 = (s2_t *) mmap(NULL, sizeof(s2_t), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, sizeof(s1_t));
    if (ptr2 == MAP_FAILED) {
        handle_error("Error [mmap() ptr2]");
    }

    printf("> %p\n", (void *) ptr1);
    printf("> %p\n", (void *) ptr2);

    fflush(stdout);  /* before fork(): do not duplicate the stdio buffer */
    pid = fork();
    if (pid < 0) {
        handle_error("Error [fork()]");
    }
    if (pid > 0) { /* parent process */
        strncpy(ptr1->name, "Monkeypox", 20);
        ptr2->col.red = 112;
    } else { /* child process */
        printf("%s\n", ptr1->name);
        printf("%i\n", ptr2->col.red);
    }

    /* remove the mapped memory segments from the address space of the process */
    if (munmap(ptr1, sizeof(s1_t)) == -1) {
        handle_error("Error [munmap() ptr1]");
    }
    if (munmap(ptr2, sizeof(s2_t)) == -1) {
        handle_error("Error [munmap() ptr2]");
    }

    /* close the shared memory segment as if it was a file */
    if (close(shm_fd) == -1) {
        handle_error("Error [close()]");
    }

    if (pid > 0) {
        wait(NULL);
        shm_unlink("/pipeautique_simple3");
    }

    return EXIT_SUCCESS;
}

void handle_error(const char *message) {
    perror(message);
    exit(EXIT_FAILURE);
}
shared_memory/src/posix_shm_spacebattle.c

View on GitHub

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

/**
 * @file posix_shm_spacebattle.c
 *
 * Example 1 of the lecture: creates a POSIX shared memory segment, sizes
 * it, projects it, works on it, then frees it.
 * Lecture: chapter os-09b "Mémoire partagée" ("Exemple 1 - créer,
 * projeter, libérer").
 *
 * Life cycle: shm_open() -> ftruncate() -> mmap() -> access -> munmap()
 * -> shm_unlink(). After mmap(), the descriptor can be closed: the
 * projection remains valid.
 * Link with \c -lrt under Linux.
 */

#define SIZE 64

typedef struct {
    int ships;
    int space_grid[SIZE][SIZE][SIZE];
} gameboard_t;

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

int main(void) {
    int fd = shm_open("/spacebattle", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        handle_error("Error [shm_open()]");
    }
    if (ftruncate(fd, sizeof(gameboard_t)) == -1) {
        handle_error("Error [ftruncate()]");
    }
    gameboard_t *gb = mmap(NULL, sizeof(gameboard_t),
                           PROT_READ | PROT_WRITE,
                           MAP_SHARED, fd, 0);
    if (gb == MAP_FAILED) {
        handle_error("Error [mmap()]");
    }
    close(fd);

    gb->ships = 3;     /* ... work on the memory */
    gb->space_grid[1][2][3] = 1;
    printf("ships = %d, segment of %zu bytes\n", gb->ships, sizeof(gameboard_t));

    munmap(gb, sizeof(gameboard_t));
    shm_unlink("/spacebattle");

    return EXIT_SUCCESS;
}
shared_memory/src/posix_shm_two_pages.c

View on GitHub

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

/**
 * @file posix_shm_two_pages.c
 *
 * Example 3 of the lecture: a segment of two pages, projected twice; a
 * structure s1_t in the first page and a structure s2_t in the second one.
 * Lecture: chapter os-09b "Mémoire partagée" ("Exemple 3 - un échange
 * plus complexe").
 *
 * The child writes into both structures, the parent waits for it, then
 * reads. The page size is asked with sysconf(): the offset given to mmap()
 * must be a multiple of it (otherwise EINVAL), and it is 16 KiB on some
 * ARM processors (compare with posix_shm_simple_3.c, which hard-codes 4096).
 * The two projections are not necessarily contiguous.
 * Link with \c -lrt under Linux.
 *
 * \code{.bash}
 *   $ ./posix_shm_two_pages
 *   > 0x7f5c3a2b7000
 *   > 0x7f5c3a2b6000
 *   Monkeypox
 *   112
 * \endcode
 */

typedef struct { float x, y, z; } vector_t;
typedef struct { unsigned char r, g, b; } color_t;

typedef struct {        /* page 0 */
    int id;
    char name[20];
    int age;
} s1_t;

typedef struct {        /* page 1 */
    vector_t vec;
    color_t col;
} s2_t;

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

int main(void) {
    long page = sysconf(_SC_PAGESIZE);
    if (page == -1) {
        handle_error("Error [sysconf()]");
    }
    int fd = shm_open("/pipeautique3", O_CREAT | O_RDWR, 0644);
    if (fd == -1) {
        handle_error("Error [shm_open()]");
    }
    if (ftruncate(fd, 2 * page) == -1) {          /* 2 pages */
        handle_error("Error [ftruncate()]");
    }
    s1_t *p1 = mmap(NULL, sizeof(s1_t),
                    PROT_READ | PROT_WRITE,
                    MAP_SHARED, fd, 0);         /* page 0 */
    if (p1 == MAP_FAILED) {
        handle_error("Error [mmap() p1]");
    }
    s2_t *p2 = mmap(NULL, sizeof(s2_t),
                    PROT_READ | PROT_WRITE,
                    MAP_SHARED, fd, page);      /* page 1 */
    if (p2 == MAP_FAILED) {
        handle_error("Error [mmap() p2]");
    }
    close(fd);
    printf("> %p\n> %p\n", (void *) p1, (void *) p2);

    fflush(stdout);                             /* before fork() */
    pid_t pid = fork();
    if (pid == -1) {
        handle_error("Error [fork()]");
    }
    if (pid == 0) {                             /* child */
        strcpy(p1->name, "Monkeypox");
        p2->col.r = 112;
        return EXIT_SUCCESS;
    }
    wait(NULL);                                 /* parent */
    printf("%s\n%d\n", p1->name, p2->col.r);

    munmap(p1, sizeof(s1_t));
    munmap(p2, sizeof(s2_t));
    shm_unlink("/pipeautique3");

    return EXIT_SUCCESS;
}
shared_memory/src/unix_shm.c

View on GitHub

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

/**
 * @file unix_shm.c
 *
 * Example using child processes sharing System V memory and POSIX semaphore.
 * Link with \c -lpthread.
 *
 * @author Alain Lebret
 * @version 1.0.2
 * @date 2016-11-01
 */

int shmid;         /* shared memory id */
int *shared_value; /* shared variable */
sem_t *sem;        /* sync semaphore */

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

/**
 * Initializes the shared memory and semaphore's value.
 * @return The number of child processes
 */
int initialize(void) {
    unsigned int number_children; /* fork count */
    unsigned int sem_value;       /* semaphore value */
    key_t shmkey;                 /* shared memory key */

    /* initialize a shared variable in shared memory */
    shmkey = ftok("/dev/null", 5);  /* valid directory name and a number */
    printf("shmkey for shared value = %d\n", shmkey);

    shmid = shmget(shmkey, sizeof(int), 0644 | IPC_CREAT);
    if (shmid < 0) {  /* shared memory error check */
        handle_fatal_error("Error [shmget()]");
    }

    shared_value = (int *) shmat(shmid, NULL, 0); /* attach to memory */
    if (shared_value == (void *) -1) {
        handle_fatal_error("Error [shmat()]");
    }
    *shared_value = 0;
    printf("shared value=%d is allocated in shared memory.\n\n", *shared_value);

    printf("How many children do you want to fork:\n");
    if (scanf("%u", &number_children) != 1) {
        fprintf(stderr, "A positive integer is expected.\n");
        shmctl(shmid, IPC_RMID, NULL); /* do not leave the segment behind */
        exit(EXIT_FAILURE);
    }

    /* 1: mutual exclusion (one child at a time in the critical section);
       > 1: several children may modify the shared value at the same time */
    printf("Enter a semaphore value: ");
    if (scanf("%u", &sem_value) != 1) {
        fprintf(stderr, "A positive integer is expected.\n");
        shmctl(shmid, IPC_RMID, NULL); /* do not leave the segment behind */
        exit(EXIT_FAILURE);
    }

    /* initialize semaphores for shared processes */
    sem = sem_open("/pSem", O_CREAT | O_EXCL, 0600, sem_value);
    if (sem == SEM_FAILED) {
        handle_fatal_error("Error [sem_open()]");
    }
    /* name of semaphore is "/pSem", semaphore is reached using this name */
    sem_unlink("/pSem");
    /* unlink prevents the semaphore existing forever */
    /* if a crash occurs during the execution         */
    printf("semaphores initialized.\n\n");
    fflush(stdout);  /* before fork(): do not duplicate the stdio buffer */

    return number_children;
}

/**
 * Manages the parent process. Parent is waiting for his child.
 */
void manage_parent(int shmid) {
    printf("Parent process (PID %ld)\n", (long) getpid());

    /* wait for all children: wait() returns -1 (errno ECHILD) when none is left */
    while (wait(NULL) > 0) {
        ;
    }
    printf("\nParent: All children have exited.\n");

    /* shared memory detach */
    shmdt(shared_value);
    shmctl(shmid, IPC_RMID, 0);

    /* cleanup semaphores */
    if (sem_close(sem) == -1) {
        handle_fatal_error("Error closing semaphore");
    }
}

/**
 * Manages the child process. Child enters critical section and modifies the
 * shared value.
 */
void manage_child(int child_number) {
    printf("Child %d process (PID %ld)\n", child_number, (long) getpid());

    sem_wait(sem);           /* P operation */
    printf("Child %d is in critical section.\n", child_number);
    sleep(1);
    *shared_value +=
            child_number % 3;  /* increment by 0, 1 or 2 based on number */
    printf("Child %d: new value = %d.\n", child_number, *shared_value);
    sem_post(sem);           /* V operation */
    printf("Child %d gets out of critical section.\n", child_number);

    if (sem_close(sem) == -1) {
        handle_fatal_error("Error closing semaphore");
    }

}

int main(void) {
    pid_t pid = 1;       /* > 0: parent, even if no child is created */
    int number_children; /* fork count */
    int child_number;

    number_children = initialize();

    /* fork child processes */
    for (child_number = 0; child_number < number_children; child_number++) {
        pid = fork();
        if (pid < 0) {
            handle_fatal_error("Error [fork()]");
        } else if (pid == 0)
            break;  /* child processes */
    }

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

    return EXIT_SUCCESS;
}
shared_memory/src/unix_shm_consumer.c

View on GitHub

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

#include <stdio.h>  /* printf() */
#include <stdlib.h> /* exit() */
#include <unistd.h> /* fork() */
#include <sys/types.h> /* pid_t */
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <signal.h>

#define DURATION 2
#define CONTINUE 1
#define STOP 0

/**
 * @file unix_shm_consumer.c
 *
 * Consumer using an IPC/System V shared memory. The program displays content
 * on the shared memory. It can be stopped using Ctrl-C.
 *
 * No synchronization: the reader may see data that is only partly updated. See the course, chapter "Synchronisation".
 */

/**
 * Structure to store the number of \c nb integers and their sum.
 */
struct data {
    int nb;
    int total;
};

typedef struct data data_t;

volatile sig_atomic_t loop = CONTINUE;

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

void stop_loop(int signal) {
    (void) signal;
    loop = STOP;
}

int main(void) {
    int id;
    key_t key;
    data_t *shared_memory;
    struct sigaction action;

    const char *home = getenv("HOME");
    if (home == NULL) {
        fprintf(stderr, "HOME is not defined: ftok() needs an existing path.\n");
        exit(EXIT_FAILURE);
    }
    key = ftok(home, 'A');
    if (key == -1) {
        handle_fatal_error("Error [ftok()]");
    }

    id = shmget(key, sizeof(data_t), 0);
    if (id == -1) {
        switch (errno) {
            case ENOENT:
                handle_fatal_error("No existing segment!");
                break;
            default:
                handle_fatal_error("Error using shmget()!");
        }
    }

    shared_memory = (data_t *) shmat(id, NULL, SHM_RDONLY);
    if (shared_memory == (void *) -1) {
        handle_fatal_error("Error using shmat()!");
    }

    loop = CONTINUE;

    action.sa_handler = stop_loop;
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    while (loop) {
        sleep(DURATION);
        printf("The sum of %d integers equals %d\n", shared_memory->nb,
               shared_memory->total);
    }

    printf("---\n");
    if (shmdt((char *) shared_memory) == -1) {
        handle_fatal_error("Error using shmdt()!");
    }

    return EXIT_SUCCESS;
}
shared_memory/src/unix_shm_producer.c

View on GitHub

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

/**
 * @file unix_shm_producer.c
 *
 * Producer using an IPC/System V shared memory. The program reads a serie of
 * integers and stores their sum in a shared memory.
 *
 * No synchronization: the reader may see data that is only partly updated. See the course, chapter "Synchronisation".
 */

/**
 * Structure to store the number of \c nb integers and their sum.
 */
struct data {
    int nb;
    int total;
};

typedef struct data data_t;

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

int main(void) {
    int id;
    int value;
    key_t key;
    struct data *shared_memory;

    const char *home = getenv("HOME");
    if (home == NULL) {
        fprintf(stderr, "HOME is not defined: ftok() needs an existing path.\n");
        exit(EXIT_FAILURE);
    }
    key = ftok(home, 'A');
    if (key == -1) {
        handle_fatal_error("Error using ftok()!");
    }

    id = shmget(key, sizeof(data_t), IPC_CREAT | IPC_EXCL | 0600);
    if (id == -1) {
        switch (errno) {
            case EEXIST:
                /* left by a previous run: list it with "ipcs -m", remove it with "ipcrm -m <id>" */
                handle_fatal_error("Segment already exists (ipcs -m, then ipcrm -m <id>)");
                break;
            default:
                handle_fatal_error("Error using shmget()!");
        }
    }

    shared_memory = (data_t *) shmat(id, NULL, 0);  /* 0: read-write attachment */
    if (shared_memory == (void *) -1) {
        handle_fatal_error("Error using shmat()!");
    }

    shared_memory->nb = 0;
    shared_memory->total = 0;

    while (1) {
        printf("+ ");
        if (scanf("%d", &value) != 1 || value == -1) { /* Exit on non-integer or -1 */
            break;
        }
        shared_memory->nb++;
        shared_memory->total += value;
        printf("The sum of %d integers equals %d\n", shared_memory->nb,
               shared_memory->total);
    }
    printf("---\n");

    if (shmdt((char *) shared_memory) == -1) {
        handle_fatal_error("Error using shmdt()!");
    }

    /* remove the memory segment */
    if (shmctl(id, IPC_RMID, NULL) == -1) {
        handle_fatal_error("Error using shmctl()/remove!");
    }

    return EXIT_SUCCESS;
}
signal/src/daemon_double_fork.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>     /* perror(), snprintf() */
#include <stdlib.h>    /* exit() */
#include <string.h>    /* strlen() */
#include <unistd.h>    /* fork(), setsid(), chdir(), dup2(), _exit() */
#include <fcntl.h>     /* open() */
#include <signal.h>    /* sigaction() */
#include <time.h>      /* time() */
#include <sys/types.h> /* pid_t */
#include <sys/stat.h>  /* umask() */

/**
 * @file daemon_double_fork.c
 * @brief Creates a daemon using the double fork technique.
 *
 * Course "Operating Systems", chapter "Signaux", part "Démons", slides
 * "Exemple de création d'un démon" and "Après le double fork".
 *
 * 1. first fork(): the initial parent exits; the child is not a group leader;
 * 2. setsid(): the child creates a new session, without controlling terminal;
 * 3. second fork(): the grandchild is not a session leader and can never
 *    reacquire a controlling terminal.
 *
 * The daemon then goes to "/", sets its umask, redirects the standard
 * descriptors to /dev/null and writes its PID in a file. It appends a line
 * to a log file every 5 seconds and stops cleanly on SIGTERM.
 *
 * The PID file is written in /tmp so that the example runs without
 * privileges (a real daemon uses /run on Linux, /var/run elsewhere).
 * Today, systemd (Linux) or launchd (macOS) start services without any
 * double fork.
 *
 * \code{.bash}
 *   $ ./daemon_double_fork
 *   $ cat /tmp/daemon_double_fork.pid
 *   $ ps -o pid,ppid,pgid,sess,tty,comm -p $(cat /tmp/daemon_double_fork.pid)
 *   $ tail /tmp/daemon_double_fork.log
 *   $ kill $(cat /tmp/daemon_double_fork.pid)
 * \endcode
 */

#define PID_FILE "/tmp/daemon_double_fork.pid"
#define LOG_FILE "/tmp/daemon_double_fork.log"
#define PERIOD   5

static volatile sig_atomic_t stop = 0;

/**
 * @brief Handler of SIGTERM: asks the daemon to stop.
 * @param sig Number of the received signal.
 */
static void handle_sigterm(int sig) {
    (void) sig;
    stop = 1;
}

/**
 * @brief Detaches the process from its terminal (double fork).
 */
static void become_daemon(void) {
    int fd;
    pid_t pid = fork();

    if (pid < 0)
        exit(EXIT_FAILURE);   /* error */
    if (pid > 0)
        _exit(EXIT_SUCCESS);  /* initial parent: end */

    if (setsid() == -1)       /* new session */
        exit(EXIT_FAILURE);

    pid = fork();
    if (pid < 0)
        exit(EXIT_FAILURE);   /* error */
    if (pid > 0)
        _exit(EXIT_SUCCESS);  /* first child: end */

    /* beginning of the daemon */
    if (chdir("/") == -1)     /* do not block the unmounting of a filesystem */
        exit(EXIT_FAILURE);
    umask(0);                 /* control the rights of created files */

    /* Standard descriptors redirected to /dev/null */
    fd = open("/dev/null", O_RDWR);
    if (fd == -1)
        exit(EXIT_FAILURE);
    dup2(fd, STDIN_FILENO);
    dup2(fd, STDOUT_FILENO);
    dup2(fd, STDERR_FILENO);
    if (fd > STDERR_FILENO)
        close(fd);
}

/**
 * @brief Writes the PID of the daemon in PID_FILE.
 * @return 0 on success, -1 on error.
 */
static int write_pid_file(void) {
    char line[32];
    int fd = open(PID_FILE, O_WRONLY | O_CREAT | O_TRUNC, 0644);

    if (fd == -1)
        return -1;
    snprintf(line, sizeof(line), "%ld\n", (long) getpid());
    if (write(fd, line, strlen(line)) == -1) {
        close(fd);
        return -1;
    }
    return close(fd);
}

int main(void) {
    struct sigaction sa;
    char line[64];
    int log_fd;

    become_daemon();

    /* Handler first: a SIGTERM sent as soon as the PID file exists is caught,
       and the PID file is removed */
    sa.sa_handler = handle_sigterm;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGTERM, &sa, NULL) == -1)
        exit(EXIT_FAILURE);

    if (write_pid_file() == -1)
        exit(EXIT_FAILURE);

    log_fd = open(LOG_FILE, O_WRONLY | O_CREAT | O_APPEND, 0644);
    if (log_fd == -1)
        exit(EXIT_FAILURE);

    /* Service loop: sleep() is interrupted by SIGTERM */
    while (!stop) {
        snprintf(line, sizeof(line), "daemon %ld alive at %ld\n",
                 (long) getpid(), (long) time(NULL));
        if (write(log_fd, line, strlen(line)) == -1)
            break;
        sleep(PERIOD);
    }

    snprintf(line, sizeof(line), "daemon %ld stopped\n", (long) getpid());
    (void) write(log_fd, line, strlen(line));
    close(log_fd);
    unlink(PID_FILE);

    return EXIT_SUCCESS;
}
signal/src/signal_01.c

View on GitHub

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

#ifdef __APPLE__
#include <sys/types.h> /* pid_t */
#include <sys/wait.h>  /* wait() */
#endif

#include <string.h>    /* memset() */

/**
 * @file signal_01.c
 *
 * A simple program that uses POSIX signals and handles SIGINT.
 */

static volatile sig_atomic_t got_sigint = 0;

/**
 * @brief Signal handler for SIGINT signal.
 * @param signal Number of the signal
 */
void handle_sigint(int signal) {
    if (signal == SIGINT) {
        got_sigint = 1;
    }
}

int main(void) {
    struct sigaction action;
    sigset_t mask, old_mask;

    /* Initialize the structure to zero before use. */
    memset(&action, '\0', sizeof(action));

    /* Set the new handler */
    action.sa_handler = &handle_sigint;
    sigemptyset(&action.sa_mask);

    /* Install the new handler of the SIGINT signal */
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    /*
     * Block SIGINT while testing the flag: with "while (!got_sigint) pause();"
     * a signal arriving between the test and pause() would be lost.
     */
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    if (sigprocmask(SIG_BLOCK, &mask, &old_mask) == -1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }

    printf("Program started. Press Ctrl-C to send SIGINT.\n");

    /* Wait for SIGINT and handle it in normal flow. */
    while (!got_sigint) {
        sigsuspend(&old_mask); /* unblocks SIGINT and waits, atomically */
    }
    sigprocmask(SIG_SETMASK, &old_mask, NULL);
    printf("SIGINT signal received!\n");

    return EXIT_SUCCESS;
}
signal/src/signal_02.c

View on GitHub

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

/**
 * @file signal_02.c
 *
 * A simple program that uses POSIX signals and handles SIGALRM.
 */

#define DURATION 5

/**
 * @brief Signal handler for SIGALRM signal.
 *
 * Only async-signal-safe functions: write() and _exit() (printf() and
 * exit() are forbidden in a handler).
 * @param signal Number of the signal
 */
void handle_alarm(int signal) {
    const char msg[] = "\nToo late!\n";

    if (signal == SIGALRM) {
        write(STDOUT_FILENO, msg, sizeof(msg) - 1);
        _exit(EXIT_FAILURE);
    }
}

int main(void) {
    struct sigaction action;
    int value;
    int remaining_time;
    int result;

    /* Initialize the structure to zero before use. */
    memset(&action, '\0', sizeof(action));

    /* Set the new handler */
    action.sa_handler = &handle_alarm;
    sigemptyset(&action.sa_mask);

    /* Install the new handler of the SIGALRM signal */
    if (sigaction(SIGALRM, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    printf("You have %d seconds to enter a number: ", DURATION);
    fflush(stdout); /* _exit() in the handler does not flush stdio buffers */
    /* The OS will send an alarm signal to the process in 'DURATION' sec. */
    alarm(DURATION);

    /* Wait for the user to enter a value */
    result = scanf("%d", &value);
    if (result < 1) {
        printf("Failed to read a valid number.\n");
        return EXIT_FAILURE;
    }

    /* Deactivate the sending of an alarm signal by the OS */
    remaining_time = alarm(0);
    printf("\nYou entered the number %d with %d seconds remaining.\n", value, remaining_time);

    return EXIT_SUCCESS;
}
signal/src/signal_03.c

View on GitHub

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

/**
 * @file signal_03.c
 *
 * A simple program that uses POSIX signals and handles SIGALRM to create a clock.
 */

volatile sig_atomic_t h = 0; /* Hours */
volatile sig_atomic_t m = 0; /* Minutes */
volatile sig_atomic_t s = 0; /* Seconds */
volatile sig_atomic_t ticked = 0;   /* set by tick() */
volatile sig_atomic_t stop = 0;     /* set by handle_sigint() */

/** 
 * @brief Signal handler for SIGINT signal.
 *
 * Only sets a flag: printf() and exit() are not async-signal-safe.
 * @param signal Number of the signal
 */
void handle_sigint(int signal) {
    if (signal == SIGINT) {
        stop = 1;
    }
}

/** 
 * @brief Signal handler for SIGALRM signal.
 *
 * Updates the clock and re-engages the alarm (alarm() is async-signal-safe).
 * The time is displayed by main(), not here.
 * @param signal Number of the signal
 */
void tick(int signal) {
    if (signal == SIGALRM) {
        s++;
        if (s == 60) {
            s = 0;
            m++;
            if (m == 60) {
                m = 0;
                h++;
                if (h == 24)
                    h = 0;
            }
        }
        ticked = 1;

        /* Re-engage the alarm */
        alarm(1);
    }
}

int main(void) {
    struct sigaction action;
    struct sigaction sigint_action;
    sigset_t mask, old_mask;

    /* Initialize the structure to zero before use. */
    memset(&action, '\0', sizeof(action));
    /* Set the new handler */
    action.sa_handler = &tick;
    sigemptyset(&action.sa_mask);
    /* Install the new handler of the SIGALRM signal */
    if (sigaction(SIGALRM, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    /* Repeat the same setup for SIGINT. */
    memset(&sigint_action, '\0', sizeof(sigint_action));
    sigint_action.sa_handler = &handle_sigint;
    sigemptyset(&sigint_action.sa_mask);
    if (sigaction(SIGINT, &sigint_action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    /* Block SIGALRM and SIGINT outside sigsuspend() (no lost wake-up) */
    sigemptyset(&mask);
    sigaddset(&mask, SIGALRM);
    sigaddset(&mask, SIGINT);
    if (sigprocmask(SIG_BLOCK, &mask, &old_mask) == -1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }

    /* Ask the OS to send a SIGALRM signal in 1 second */
    alarm(1);

    /* Waiting for signals: use <Ctrl-C> to exit */
    while (!stop) {
        sigsuspend(&old_mask);
        if (ticked) {
            ticked = 0;
            printf("%d:%d:%d\n", (int) h, (int) m, (int) s);
        }
    }
    sigprocmask(SIG_SETMASK, &old_mask, NULL);

    printf("Terminating...\n");

    return EXIT_SUCCESS;
}
signal/src/signal_04.c

View on GitHub

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

/**
 * @file signal_04.c
 *
 * A simple program that uses POSIX signals and handles SIGCHLD.
 */

static volatile sig_atomic_t child_exited = 0;
static volatile sig_atomic_t last_child = 0;   /* PID of the last reaped child */

/**
 * @brief Defines a new handler of the SIGCHLD signal in charge of suppressing
 * zombies.
 *
 * Only async-signal-safe operations are used here: waitpid() and assignments
 * to sig_atomic_t variables. The message is printed later, in the normal
 * flow of the program (printf() must never be called from a handler).
 * @param signal Number of the signal.
 */
void handle_sigchild(int signal) {
    pid_t child;
    int saved_errno = errno;   /* waitpid() may modify errno */

    if (signal == SIGCHLD) {
        while ((child = waitpid(-1, NULL, WNOHANG)) > 0) {
            last_child = (sig_atomic_t)child;
        }
        child_exited = 1;
    }
    errno = saved_errno;
}

/**
 * @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 Installs the SIGCHLD handler. Called before fork(): the handler is
 * then in place even if the child ends before the parent runs again.
 */
void install_sigchld_handler(void) {
    struct sigaction action;

    /* Initialize the structure to zero before use. */
    memset(&action, '\0', sizeof(action));
    /* Set the new handler */
    action.sa_handler = &handle_sigchild;
    sigemptyset(&action.sa_mask);
    /* We ensure that certain system calls are automatically restarted if
     * interrupted by a signal; no SIGCHLD when a child is only stopped */
    action.sa_flags = SA_RESTART | SA_NOCLDSTOP;

    /* Install the new handler of the SIGCHLD signal */
    if (sigaction(SIGCHLD, &action, NULL) == -1) {
        handle_fatal_error_and_exit("sigaction");
    }
}

/**
 * @brief Manages the parent process.
 */
void manage_parent(void) {
    printf("Parent process (PID %ld)\n", (long) getpid());

    while (!child_exited) {
        printf("Parent: I am working...\n");
        sleep(2);
    }

    printf("My child (%ld) died. He will not be a zombie.\n", (long) last_child);
    printf("Parent: My child has exited, so I can stop working :-)\n");
}

/**
 * @brief Manages the child process. 
 *
 * The child simulates work for 10 seconds.
 */
void manage_child(void) {
    printf("Child process (PID %ld)\n", (long) getpid());
    printf("Child: I am doing some stuff for 10 seconds...\n");
    sleep(10);
    exit(EXIT_SUCCESS);
}

int main(void) {
    pid_t pid;

    install_sigchld_handler(); /* before fork() */
    pid = fork();

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

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

    return EXIT_SUCCESS;
}
signal/src/signal_05.c

View on GitHub

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

/**
 * @file signal_05.c
 *
 * A simple program that uses POSIX signals and handles many signals.
 */

volatile sig_atomic_t exit_flag = 0;
volatile sig_atomic_t received = 0; /* number of the last received signal */

/**
 * @brief Records the received signal number; main() displays it.
 *
 * printf() is not async-signal-safe: the handler only sets flags.
 * @param signal Number of the signal.
 */
void handle(int signal) {
    received = signal;

    if (signal == SIGINT || signal == SIGTERM) {
        exit_flag = 1;
    }
}

int main(void) {
    struct sigaction action;
    sigset_t mask, old_mask;

    /* Initialize the structure to zero before use. */
    memset(&action, '\0', sizeof(action));
    /* Set the new handler */
    action.sa_handler = &handle;
    /* We do not block any specific signal */
    sigemptyset(&action.sa_mask);

    /* Three signals will be handled by the process */
    if (sigaction(SIGINT, &action, 0) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }
    if (sigaction(SIGQUIT, &action, 0) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }
    if (sigaction(SIGTERM, &action, 0) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    /* Block the three signals outside sigsuspend() (no lost wake-up) */
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGQUIT);
    sigaddset(&mask, SIGTERM);
    if (sigprocmask(SIG_BLOCK, &mask, &old_mask) == -1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }

    while (!exit_flag) {
        sigsuspend(&old_mask); /* Wait for a signal */
        printf("Signal number %d has been received.\n", (int) received);
    }
    sigprocmask(SIG_SETMASK, &old_mask, NULL);

    printf("Exiting more gracefully.\n");

    return EXIT_SUCCESS;
}
signal/src/signal_06.c

View on GitHub

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

/**
 * @file signal_06.c
 *
 * A simple program that uses POSIX signals and manages masks to block signals.
 */

#define NBR_SIGNALS 2

/** A group of signals to be blocked by the process */
int signals[NBR_SIGNALS] = {SIGINT, SIGTERM};

/** An array to store the old signal handlers */

int main(void) {
    int i;
    sigset_t new_mask;
    sigset_t old_mask;
    sigset_t pending_signals;

    /*
     * Create a mask to block the two signals.
     */
    sigemptyset(&new_mask);
    for (i = 0; i < NBR_SIGNALS; i++) {
        sigaddset(&new_mask, signals[i]);
    }

    /*
     * Exchange old and new masks
     */
    if (sigprocmask(SIG_SETMASK, &new_mask, &old_mask) == -1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }

    /*
     * Sleep for 20 seconds (maybe enough to try sending CTRL-C and SIGTERM
     * signals)...
     */
    printf("20 seconds to send <CTRL>-C and kill -15 %ld to this process\n", (long) getpid());
    sleep(20);

    /* Get the list of pending signals */
    sigpending(&pending_signals);

    /* Decode pending signals (NSIG is not POSIX: test the blocked ones) */
    for (i = 0; i < NBR_SIGNALS; i++) {
        if (sigismember(&pending_signals, signals[i])) {
            printf("Pending signal %d has been blocked.\n", signals[i]);
        }
    }

    /*
     * Unblocking signals: a pending SIGINT or SIGTERM is delivered now and
     * its default action terminates the process before the next message
     * (without flushing stdio buffers: hence the fflush()).
     */
    fflush(stdout);
    sigprocmask(SIG_SETMASK, &old_mask, NULL);
    printf("\nSignals unblocked. Normal operation resumed.\n");

    return EXIT_SUCCESS;
}
signal/src/signal_07.c

View on GitHub

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

/**
 * @file signal_07.c
 *
 * A simple program that uses POSIX signals and handles the SIGUSR1 signal.
 */

volatile sig_atomic_t nb_calls = 7;

/**
 * @brief Handles the signal SIGUSR1 by decrementing \em nb_calls.
 *
 * No printf() here (not async-signal-safe): the child displays the value.
 * @param signal Number of the received signal.
 */
void handle_seven_lives(int signal) {
    if (signal == SIGUSR1) {
        nb_calls--;
    }
}

/**
 * @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. 
 *
 * It decrements the number of lives before sending the signal SIGUSR1 to 
 * his child and waiting for his death.
 */
void manage_parent(pid_t child) {
    int lives = 7; /* the parent's own counter (nb_calls belongs to the child's handler) */

    printf("Parent process (PID %ld)\n", (long) getpid());

    while (lives-- != 0) {
        sleep(2);
        printf("Parent: sending SIGUSR1 to the child %ld...\n", (long) child);
        kill(child, SIGUSR1);
    }

    waitpid(child, NULL, 0); /* Wait for the child to exit */
    printf("Parent: Child exited. Parent exiting.\n");

    exit(EXIT_SUCCESS);
}

/**
 * @brief Manages the child process. 
 *
 * It configures the handler to react to the signal SIGUSR1. The child process
 * exits when \em nb_calls reaches 0. SIGUSR1 has been blocked before fork():
 * a signal sent before the handler is installed stays pending instead of
 * killing the child, and sigsuspend() waits without active loop nor race.
 * @param old_mask The signal mask before SIGUSR1 was blocked.
 */
void manage_child(const sigset_t *old_mask) {
    struct sigaction managing_lives;

    printf("Child process (PID %ld)\n", (long) getpid());

    /* Initialize the structure to zero before use. */
    memset(&managing_lives, '\0', sizeof(managing_lives));

    /* Set the new handler */
    managing_lives.sa_handler = &handle_seven_lives;
    sigemptyset(&managing_lives.sa_mask);

    /* Install the new handler of the SIGUSR1 signal */
    if (sigaction(SIGUSR1, &managing_lives, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    while (nb_calls != 0) {
        sigsuspend(old_mask); /* unblocks SIGUSR1 and waits, atomically */
        printf("Still have %d lives....\n", (int) nb_calls);
    }

    exit(EXIT_SUCCESS);
}

int main(void) {
    pid_t pid;
    sigset_t mask, old_mask;

    /* Block SIGUSR1 before fork(): the child inherits this mask */
    sigemptyset(&mask);
    sigaddset(&mask, SIGUSR1);
    if (sigprocmask(SIG_BLOCK, &mask, &old_mask) == -1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }

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

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

    return EXIT_SUCCESS;
}
signal/src/signal_08a.c

View on GitHub

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

/**
 * @file signal_08a.c
 *
 * A simple program to handle the SIGUSR1 signal. 
 * Open another terminal while running this program and execute:
 * kill -s SIGUSR1 <PID>
 * What if using the following command?
 * kill -s SIGINT <PID> 
 */

volatile sig_atomic_t got_usr1;

/**
 * @brief Handles the signal SIGUSR1.
 */
void sigusr1_handler(int signal) {
    (void) signal;
    got_usr1 = 1;
}

/**
 * @brief Handles the signal SIGINT with async-signal-safe functions only
 * (write() and _exit(), not printf() and exit()).
 */
void sigint_handler(int signal) {
    const char msg[] = "SIGINT received, exiting.\n";

    (void) signal;
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    _exit(EXIT_SUCCESS);
}

int main(void) {
    struct sigaction action_usr1;
    struct sigaction action_int;

    got_usr1 = 0;

    /* Set the new handler */
    action_usr1.sa_handler = sigusr1_handler;
    /* Clear the flags (another way to do a memset) */
    action_usr1.sa_flags = 0;
    /* Clear the mask */
    sigemptyset(&action_usr1.sa_mask);

    /* Repeat the same setup for SIGINT. */
    action_int.sa_handler = sigint_handler;
    action_int.sa_flags = 0;
    sigemptyset(&action_int.sa_mask);

    if (sigaction(SIGUSR1, &action_usr1, NULL) == -1) {
        perror("Error using sigaction for SIGUSR1");
        exit(EXIT_FAILURE);
    }

    if (sigaction(SIGINT, &action_int, NULL) == -1) {
        perror("Error using sigaction for SIGINT");
        exit(EXIT_FAILURE);
    }

    while (!got_usr1) {
        printf("PID %ld: working hard...\n", (long) getpid());
        sleep(1);
    }

    printf("Done by SIGUSR1!\n");

    return EXIT_SUCCESS;
}
signal/src/signal_08b.c

View on GitHub

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

/**
 * @file signal_08b.c
 *
 * A simple program to handle the SIGUSR1 signal, but this time we 
 * mask other signals. 
 * Open another terminal while running this program and execute:
 * kill -s SIGUSR1 <PID>
 * What if using the following command?
 * kill -s SIGINT <PID>
 */

volatile sig_atomic_t got_usr1;

/**
 * @brief Handles the signal SIGUSR1.
 */
void sigusr1_handler(int signal) {
    if (signal == SIGUSR1) {
        got_usr1 = 1;
    }
}

int main(void) {
    struct sigaction action;
    sigset_t the_new_mask;

    got_usr1 = 0;

    /* Initialize the_new_mask to full, including all signals to be blocked */
    sigfillset(&the_new_mask);
    /* Remove SIGUSR1 from the_new_mask */
    sigdelset(&the_new_mask, SIGUSR1);
    /* Change the signal mask with the_new_mask */
    if (sigprocmask(SIG_SETMASK, &the_new_mask, NULL) == -1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }


    /* Set the new handler */
    action.sa_handler = sigusr1_handler;
    /* Clear the flags (another way to do a memset) */
    action.sa_flags = 0;
    /* Apply the_new_mask */
    action.sa_mask = the_new_mask;

    if (sigaction(SIGUSR1, &action, NULL) == -1) {
        perror("Error using sigaction");
        exit(EXIT_FAILURE);
    }

    while (!got_usr1) {
        printf("PID %ld: working hard...\n", (long) getpid());
        sleep(1);
    }

    printf("Done by SIGUSR1!\n");

    return EXIT_SUCCESS;
}
signal/src/signal_08c.c

View on GitHub

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

/**
 * @file signal_08c.c
 *
 * A simple program to handle SIGUSR1 and SIGUSR2 signals with two distinct
 * handlers, but this time we mask other signals.
 * Open another terminal while running this program and execute:
 * kill -s SIGUSR1 <PID>
 * What if using the following command?
 * kill -s SIGINT <PID>
 * To stop the program: kill -s SIGKILL <PID>
 */

/**
 * @brief Handles SIGUSR1 (write() is async-signal-safe, printf() is not).
 */
void do_when_sigusr1(int sig) {
    const char msg[] = "Have received one SIGUSR1\n";

    (void) sig;
    int saved_errno = errno; /* write() may change errno: restore it for main() */
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    errno = saved_errno;
}

/**
 * @brief Handles SIGUSR2 (write() is async-signal-safe, printf() is not).
 */
void do_when_sigusr2(int sig) {
    const char msg[] = "Have received one SIGUSR2\n";

    (void) sig;
    int saved_errno = errno; /* write() may change errno: restore it for main() */
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    errno = saved_errno;
}

int main(void) {
    int is_ok;
    sigset_t set;
    sigset_t oset;
    struct sigaction action;

    /* Add all signals to the mask (SIGKILL and SIGSTOP cannot be blocked) */
    sigfillset(&set);
    /* Remove SIGUSR1 and SIGUSR2 from the mask */
    sigdelset(&set, SIGUSR1);
    sigdelset(&set, SIGUSR2);
    /* Install the mask to receive only SIGUSR1 and SIGUSR2 */
    is_ok = sigprocmask(SIG_SETMASK, &set, &oset);

    if (is_ok == -1) {
        perror("PB");
    }
    if (sigismember(&set, SIGUSR1) || sigismember(&set, SIGUSR2)) {
        printf("Problem with the mask\n");
        exit(EXIT_FAILURE);
    }
    if (!sigismember(&oset, SIGUSR1) && !sigismember(&oset, SIGUSR2)) {
        printf("The old mask was not blocking signals\n");
    }
    printf("PID %ld: only SIGUSR1 or SIGUSR2 may be received\n", (long) getpid());

    /* Initialize the structure to zero before use. */
    memset(&action, '\0', sizeof(action));

    action.sa_mask = set;
    action.sa_handler = do_when_sigusr1;
    if (sigaction(SIGUSR1, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    action.sa_handler = do_when_sigusr2;
    if (sigaction(SIGUSR2, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    while (1) {
        sleep(1);
    }

    return 0;
}
signal/src/signal_09.c

View on GitHub

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

/**
 * @file signal_09.c
 *
 * A simple program that setups a signal handler with 3 arguments, including
 * siginfo_t.
 */

static volatile sig_atomic_t got_sigterm = 0;
static volatile sig_atomic_t got_sigint = 0;
static volatile sig_atomic_t sender_pid = -1;
static volatile sig_atomic_t sender_uid = -1;

void hdl(int signal, siginfo_t *siginfo, void *context) {
    (void) context;
    if (signal == SIGTERM) {
        sender_pid = (sig_atomic_t) siginfo->si_pid;
        sender_uid = (sig_atomic_t) siginfo->si_uid;
        got_sigterm = 1;
    }
}

void sigint_handler(int signal) {
    if (signal == SIGINT) {
        got_sigint = 1;
    }
}

int main(void) {
    struct sigaction action;
    struct sigaction sigint_action;
    sigset_t mask, old_mask;

    /* Initialize the structure to zero before use. */
    memset(&action, '\0', sizeof(action));
    /* Use the sa_sigaction field because the handler has two additional parameters */
    action.sa_sigaction = &hdl;
    sigemptyset(&action.sa_mask);
    /* The SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler. */
    action.sa_flags = SA_SIGINFO;

    if (sigaction(SIGTERM, &action, NULL) < 0) {
        perror("Error using sigaction for SIGTERM");
        exit(EXIT_FAILURE);
    }

    /* Normal signal handler installation for SIGINT */
    memset(&sigint_action, '\0', sizeof(sigint_action));
    sigint_action.sa_handler = sigint_handler;
    sigemptyset(&sigint_action.sa_mask);
    if (sigaction(SIGINT, &sigint_action, NULL) < 0) {
        perror("Error using sigaction for SIGINT");
        exit(EXIT_FAILURE);
    }

    /* Block SIGTERM and SIGINT outside sigsuspend() (no lost wake-up) */
    sigemptyset(&mask);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGINT);
    if (sigprocmask(SIG_BLOCK, &mask, &old_mask) == -1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }

    printf("PID %ld: send SIGTERM (kill %ld), then SIGINT (Ctrl-C) to exit\n",
           (long) getpid(), (long) getpid());

    while (!got_sigint) {
        sigsuspend(&old_mask);
        if (got_sigterm) {
            printf("Sending PID: %ld, UID: %ld\n", (long) sender_pid, (long) sender_uid);
            got_sigterm = 0;
        }
    }
    sigprocmask(SIG_SETMASK, &old_mask, NULL);
    printf("SIGINT received, exiting.\n");

    return EXIT_SUCCESS;
}
signal/src/signal_kill_child.c

View on GitHub

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

/**
 * @file signal_kill_child.c
 * @brief The parent sends SIGUSR1 to its child with kill().
 *
 * Course "Operating Systems", chapter "Signaux", slide
 * "Exemple parent -> enfant".
 *
 * The child installs no handler: the default action of SIGUSR1 terminates
 * it. The parent then decodes the status returned by waitpid().
 *
 * Note: without the test pid == -1, a failed fork() would lead to
 * kill(-1, SIGUSR1), which sends the signal to ALL your processes.
 *
 * \code{.bash}
 *   $ ./signal_kill_child
 *   Parent: sending SIGUSR1 to the child ...
 *   Parent: child ... killed by signal ... (SIGUSR1)
 * \endcode
 */

int main(void) {
    int status;
    pid_t pid = fork();

    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if (pid == 0) {
        pause();     /* child: killed by SIGUSR1 */
        return EXIT_SUCCESS;
    }
    sleep(1);        /* parent: sends SIGUSR1 */
    printf("Parent: sending SIGUSR1 to the child %ld\n", (long) pid);
    if (kill(pid, SIGUSR1) == -1) {
        perror("kill");
        return EXIT_FAILURE;
    }
    if (waitpid(pid, &status, 0) == -1) {
        perror("waitpid");
        return EXIT_FAILURE;
    }

    if (WIFSIGNALED(status)) {
        printf("Parent: child %ld killed by signal %d%s\n", (long) pid,
               WTERMSIG(status),
               WTERMSIG(status) == SIGUSR1 ? " (SIGUSR1)" : "");
    } else if (WIFEXITED(status)) {
        printf("Parent: child %ld exited with code %d\n", (long) pid,
               WEXITSTATUS(status));
    }

    return EXIT_SUCCESS;
}
signal/src/signal_sigsuspend.c

View on GitHub

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

/**
 * @file signal_sigsuspend.c
 * @brief Waits for SIGUSR1 without race condition using sigsuspend().
 *
 * Course "Operating Systems", chapter "Signaux", slides
 * "Communiquer avec le programme principal", "Erreur classique : tester
 * puis pause()" and "Attendre sans situation de compétition : sigsuspend()".
 *
 * The handler only sets a volatile sig_atomic_t flag. With the naive loop
 * "while (!recu) pause();", a signal arriving between the test and pause()
 * would be lost. Here SIGUSR1 is blocked during the test (it stays pending)
 * and sigsuspend() atomically restores the old mask and waits.
 *
 * \code{.bash}
 *   $ ./signal_sigsuspend &
 *   PID 12345: waiting for SIGUSR1 (kill -USR1 12345)
 *   $ kill -USR1 12345
 *   SIGUSR1 received, normal flow resumed.
 * \endcode
 */

static volatile sig_atomic_t recu = 0;

/**
 * @brief Handler of SIGUSR1: only sets the flag (async-signal safe).
 * @param sig Number of the received signal.
 */
static void gestionnaire(int sig) {
    (void) sig;
    recu = 1;          /* safe operation */
}

int main(void) {
    struct sigaction sa;
    sigset_t masque, ancien;

    /* Install the handler of SIGUSR1 */
    sa.sa_handler = gestionnaire;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGUSR1, &sa, NULL) == -1) {
        perror("sigaction");
        return EXIT_FAILURE;
    }

    /* Block SIGUSR1 before testing the flag */
    sigemptyset(&masque);
    sigaddset(&masque, SIGUSR1);
    if (sigprocmask(SIG_BLOCK, &masque, &ancien) == -1) {
        perror("sigprocmask");
        return EXIT_FAILURE;
    }

    printf("PID %ld: waiting for SIGUSR1 (kill -USR1 %ld)\n",
           (long) getpid(), (long) getpid());
    fflush(stdout);

    while (!recu) {
        sigsuspend(&ancien);  /* unblocks and waits, atomically */
    }

    /* Restore the previous mask */
    sigprocmask(SIG_SETMASK, &ancien, NULL);

    printf("SIGUSR1 received, normal flow resumed.\n");

    return EXIT_SUCCESS;
}
timers/src/linux_clock.c

View on GitHub

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

/**
 * @file linux_clock.c
 *
 * A simple program that uses POSIX timers and handles SIGRTMIN to create a clock.
 * Linux only: macOS has neither timer_create() nor SIGRTMIN (see macosx_clock.c).
 */

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>

volatile sig_atomic_t h = 0; /* Hours */
volatile sig_atomic_t m = 0; /* Minutes */
volatile sig_atomic_t s = 0; /* Seconds */
volatile sig_atomic_t ticked = 0; /* set by tick() */
volatile sig_atomic_t stop = 0;   /* set by handle_sigint() */

/** 
 * @brief Signal handler for SIGINT signal.
 * @param signal Number of the signal
 */
void handle_sigint(int signal) 
{
    /* Only a flag: printf() and exit() are not async-signal-safe */
    if (signal == SIGINT) {
        stop = 1;
    }
}

/** 
 * @brief Signal handler for real-time signal.
 * @param signal Number of the signal
 */
void tick(int signal) 
{
    if (signal == SIGRTMIN) {
        s++;
        if (s == 60) {
            s = 0;
            m++;
            if (m == 60) {
                m = 0;
                h++;
                if (h == 24)
                    h = 0;
            }
        }
        ticked = 1;   /* the time is displayed by main() */
        /* No need to re-arm manually */
    }
}

int main(void) 
{
    struct sigaction action;
    struct sigaction sigint_action;
    sigset_t mask, old_mask;

    /* Initialize the structure to zero before use. */
    memset(&action, 0, sizeof(action));
    /* Set the new handler */
    action.sa_handler = &tick;
    sigemptyset(&action.sa_mask);
    action.sa_flags = SA_RESTART;
    /* Install the new handler of the SIGRTMIN signal */
    if (sigaction(SIGRTMIN, &action, NULL) == -1) {
        perror("sigaction SIGRTMIN");
        exit(EXIT_FAILURE);
    }

    /* Repeat the same setup for SIGINT. */
    memset(&sigint_action, 0, sizeof(sigint_action));
    sigint_action.sa_handler = &handle_sigint;
    sigemptyset(&sigint_action.sa_mask);
    sigint_action.sa_flags = SA_RESTART;
    if (sigaction(SIGINT, &sigint_action, NULL) == -1) {
        perror("sigaction SIGINT");
        exit(EXIT_FAILURE);
    }

    /* Block SIGRTMIN and SIGINT: they are only received inside sigsuspend() */
    sigemptyset(&mask);
    sigaddset(&mask, SIGRTMIN);
    sigaddset(&mask, SIGINT);
    if (sigprocmask(SIG_BLOCK, &mask, &old_mask) == -1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }

    /* Create the POSIX timer */
    struct sigevent sev;
    memset(&sev, 0, sizeof(sev));
    sev.sigev_notify = SIGEV_SIGNAL;
    sev.sigev_signo = SIGRTMIN;

    timer_t timerid;
    if (timer_create(CLOCK_REALTIME, &sev, &timerid) == -1) {
        perror("timer_create");
        exit(EXIT_FAILURE);
    }

    /* Arm the timer for each second */
    struct itimerspec its;
    its.it_value.tv_sec = 1;
    its.it_value.tv_nsec = 0;
    its.it_interval.tv_sec = 1;
    its.it_interval.tv_nsec = 0;

    if (timer_settime(timerid, 0, &its, NULL) == -1) {
        perror("timer_settime");
        exit(EXIT_FAILURE);
    }

    printf("Timer is armed (Linux, SIGRTMIN). Press Ctrl-C to quit.\n");

    /* Waiting for signals (blocked outside sigsuspend(): no lost wake-up) */
    while (!stop) {
        sigsuspend(&old_mask);
        if (ticked) {
            ticked = 0;
            printf("%d:%d:%d\n", (int) h, (int) m, (int) s);
        }
    }
    sigprocmask(SIG_SETMASK, &old_mask, NULL);
    printf("Terminating...\n");

    return EXIT_SUCCESS;
}
timers/src/macosx_clock.c

View on GitHub

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

/**
 * @file macosx_clock.c
 *
 * A simple program that uses timer and handles SIGALRM to create a clock.
 */

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

volatile sig_atomic_t h = 0;
volatile sig_atomic_t m = 0;
volatile sig_atomic_t s = 0;
volatile sig_atomic_t ticked = 0; /* set by tick() */
volatile sig_atomic_t stop = 0;   /* set by handle_sigint() */

void handle_sigint(int signal) {
    /* Only a flag: printf() and exit() are not async-signal-safe */
    if (signal == SIGINT) {
        stop = 1;
    }
}

void tick(int signal) {
    if (signal == SIGALRM) {
        s++;
        if (s == 60) {
            s = 0;
            m++;
            if (m == 60) {
                m = 0;
                h++;
                if (h == 24)
                    h = 0;
            }
        }
        ticked = 1;   /* the time is displayed by main() */
    }
}

int main(void) {
    struct sigaction action;
    struct sigaction sigint_action;
    sigset_t mask, old_mask;

    /* Initialize the structure to zero before use. */
    memset(&action, 0, sizeof(action));
    /* Set the new handler */
    action.sa_handler = &tick;
    sigemptyset(&action.sa_mask);
    action.sa_flags = SA_RESTART;
    /* Install the new handler of the SIGALRM signal */
    if (sigaction(SIGALRM, &action, NULL) == -1) {
        perror("sigaction SIGALRM");
        exit(EXIT_FAILURE);
    }

    /* Repeat the same setup for SIGINT. */
    memset(&sigint_action, 0, sizeof(sigint_action));
    sigint_action.sa_handler = &handle_sigint;
    sigemptyset(&sigint_action.sa_mask);
    sigint_action.sa_flags = SA_RESTART;
    if (sigaction(SIGINT, &sigint_action, NULL) == -1) {
        perror("sigaction SIGINT");
        exit(EXIT_FAILURE);
    }

    /* Block SIGALRM and SIGINT: they are only received inside sigsuspend() */
    sigemptyset(&mask);
    sigaddset(&mask, SIGALRM);
    sigaddset(&mask, SIGINT);
    if (sigprocmask(SIG_BLOCK, &mask, &old_mask) == -1) {
        perror("sigprocmask");
        exit(EXIT_FAILURE);
    }

    /* On macOS, POSIX timers are not available, we must use setitimer() */
    struct itimerval itv;
    itv.it_value.tv_sec = 1;
    itv.it_value.tv_usec = 0;
    itv.it_interval.tv_sec = 1;
    itv.it_interval.tv_usec = 0;

    if (setitimer(ITIMER_REAL, &itv, NULL) == -1) {
        perror("setitimer");
        exit(EXIT_FAILURE);
    }

    printf("Timer is armed (macOS uses setitimer() and SIGALRM). Press Ctrl-C to quit.\n");

    /* Waiting for signals (blocked outside sigsuspend(): no lost wake-up) */
    while (!stop) {
        sigsuspend(&old_mask);
        if (ticked) {
            ticked = 0;
            printf("%d:%d:%d (macOS, SIGALRM via setitimer)\n", (int) h, (int) m, (int) s);
        }
    }
    sigprocmask(SIG_SETMASK, &old_mask, NULL);
    printf("Terminating...\n");

    return EXIT_SUCCESS;
}
timers/src/posix_timer_tic.c

View on GitHub

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

/**
 * @file posix_timer_tic.c
 * @brief A periodic POSIX timer that prints "tic" (Linux only).
 *
 * Course "Operating Systems", chapter "Signaux", part "Minuteries POSIX",
 * slides "Exemple (1/3)" to "Exemple (3/3)".
 *
 * The timer uses CLOCK_MONOTONIC and notifies the process with SIGRTMIN.
 * The default action of SIGRTMIN terminates the process: a handler is
 * therefore mandatory. First expiration after 1.02 s, then every 500 ms.
 * Stop with Ctrl-C.
 *
 * timer_create() and SIGRTMIN do not exist on macOS: see macosx_clock.c
 * (setitimer()). With glibc < 2.34, link with -lrt.
 *
 * \code{.bash}
 *   $ ./posix_timer_tic
 *   tic
 *   tic
 *   ^C
 * \endcode
 */

/**
 * @brief Handler of SIGRTMIN: write() is async-signal safe, printf() is not.
 * @param sig Number of the received signal.
 */
static void gestionnaire(int sig) {
    (void) sig;
    const char msg[] = "tic\n";
    int saved_errno = errno; /* write() may change errno: restore it for main() */
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    errno = saved_errno;
}

int main(void) {
    struct sigaction sa;
    struct sigevent sev;
    struct itimerspec its;
    timer_t timerid;

    /* (1/3) Install the handler */
    sa.sa_handler = gestionnaire;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGRTMIN, &sa, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    /* (2/3) Create the timer */
    memset(&sev, 0, sizeof(sev));
    sev.sigev_notify = SIGEV_SIGNAL;
    sev.sigev_signo = SIGRTMIN;  /* chosen signal */

    if (timer_create(CLOCK_MONOTONIC, &sev,
                     &timerid) == -1) {
        perror("timer_create");
        exit(EXIT_FAILURE);
    }

    /* (3/3) Arm the timer */
    /* first expiration after 1 s and 20 ms */
    its.it_value.tv_sec = 1;
    its.it_value.tv_nsec = 20000000L;
    /* then every 500 ms */
    its.it_interval.tv_sec = 0;
    its.it_interval.tv_nsec = 500000000L;

    if (timer_settime(timerid, 0, &its, NULL) == -1) {
        perror("timer_settime");
        exit(EXIT_FAILURE);
    }
    for (;;)
        pause();

    /* Unreachable: use <Ctrl-C> to exit (timer_delete(timerid) otherwise) */
}
unix_messages/include/message.h

View on GitHub

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

/**
 * @file message.h
 * Defines the structure and functions for handling messages in a message queue system.
 *
 * @author Alain Lebret
 * @version 1.0
 * @date 2012-04-10
 */

#define MESSAGE_SIZE     1024
#define MSG_TYPE_HANDOUT   22

/** Structure of a message */
typedef struct content {
    char buffer[MESSAGE_SIZE];
} content_t;

typedef struct message {
    long type;
    content_t content;
} message_t;

/**
 * Displays the type and content of the given message.
 * @param message Pointer to the message to display.
 */
void msg_display(message_t *message);

/**
 * Fills the given message with the specified character.
 * @param message Pointer to the message to fill.
 * @param val The character used to fill the message (no final '\0').
 */
void msg_fill(message_t *message, char val);

#endif
unix_messages/src/message.c

View on GitHub

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

#include "message.h"

/**
 * @file message.c
 *
 * @author Alain Lebret
 * @author Bruno Jacob <Bruno.Jacob@lium.univ-lemans.fr>
 * @version 1.1 - 2016-10-01
 */

/**
 * Displays the type and content of the given message.
 * @param message Pointer to the message to be displayed.
 */
void msg_display(message_t *message) {
    if (message == NULL) {
        fprintf(stderr, "Error: NULL pointer provided to msg_display().\n");
        return;
    }

    printf("\tType: %ld\n", message->type);
    /* The buffer is not always null-terminated (see msg_fill()): bounded print */
    printf("\tContent: %.*s\n", MESSAGE_SIZE, message->content.buffer);
}

/**
 * Fills the given message with the specified character.
 * @param message Pointer to the message to be filled.
 * @param value Character used to fill the message buffer.
 */
void msg_fill(message_t *message, char value) {
    int i;

    if (message == NULL) {
        fprintf(stderr, "Error: NULL pointer provided to msg_fill.\n");
        return;
    }

    /* Type of the message */
    message->type = MSG_TYPE_HANDOUT;

    /* Content */
    for (i = 0; i < MESSAGE_SIZE; i++) {
        message->content.buffer[i] = value;
    }
}
unix_messages/src/test_message.c

View on GitHub

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

/**
 * @file test_message.c
 * @brief Test message handling functions.
 */

int main(int argc, char *argv[]) {
    (void) argc;
    message_t message;
    struct timeval time;
    double begin;
    double end;

    printf("\n---------- Beginning of %s ----------\n", argv[0]);

    gettimeofday(&time, NULL);
    begin = time.tv_sec + (time.tv_usec / 1000000.0);

    printf("Filling the message with some A\n");
    msg_fill(&message, 'A');

    printf("Displaying of the message\n");
    msg_display(&message);

    gettimeofday(&time, NULL);
    end = time.tv_sec + (time.tv_usec / 1000000.0);

    printf("\nDuration of the program %s = %.6lf seconds.\n", argv[0], end - begin);

    return EXIT_SUCCESS;
}
unix_messages/src/unix_msg_recv.c

View on GitHub

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

#include "message.h"

/**
 * @file unix_msg_recv.c
 *
 * Consumer program using a System V IPC message mechanism.
 * Run unix_msg_send first (it creates the queue). The queue persists after
 * the programs end: observe it with "ipcs -q", remove it with "ipcrm -q <id>",
 * or run "./unix_msg_recv -r", which removes it after reading (msgctl()).
 */

#define MSGQ_KEY 1234
#define MSGQ_PERM 0600
/* Fixed key for the demonstration (see ftok() in the course); permissions
 * 0600: only the owner can use the queue. */

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

/**
 * Returns the message queue ID for the given key.
 */
int get_msgq_id(key_t key) {
    int msgq_id;
    int msg_flag;

    msg_flag = MSGQ_PERM;
    msgq_id = msgget(key, msg_flag);

    if (msgq_id < 0) {
        handle_fatal_error("Error using msgget()!");
    }

    return msgq_id;
}

int main(int argc, char *argv[]) {
    int msgq_id;
    message_t message;
    int remove_queue = (argc == 2 && strcmp(argv[1], "-r") == 0);

    msgq_id = get_msgq_id(MSGQ_KEY);

    /* Receive an answer of message type MSG_TYPE_HANDOUT */
    if (msgrcv(msgq_id, &message, MESSAGE_SIZE, MSG_TYPE_HANDOUT, 0) < 0) {
        handle_fatal_error("Error using msgrcv()!");
    }

    msg_display(&message);

    if (remove_queue) {
        if (msgctl(msgq_id, IPC_RMID, NULL) == -1) {
            handle_fatal_error("Error using msgctl(IPC_RMID)");
        }
        printf("Queue removed.\n");
    }

    return EXIT_SUCCESS;
}
unix_messages/src/unix_msg_send.c

View on GitHub

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

/**
 * @file unix_msg_send.c
 *
 * Producer program using a System V IPC message mechanism.
 */

#define MSGQ_KEY 1234
#define MSGQ_PERM (IPC_CREAT | 0600)
/* Fixed key for the demonstration (see ftok() in the course); permissions
 * 0600: only the owner can use the queue. */

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

/**
 * Returns the message queue ID for the given key
 */
int get_msgq_id(key_t key) {
    int msgq_id;
    int msg_flag;

    msg_flag = MSGQ_PERM;
    msgq_id = msgget(key, msg_flag);
    if (msgq_id < 0) {
        handle_fatal_error("Error using msgget()!");
    }

    return msgq_id;
}

int main(void) {
    int msgq_id;
    message_t message;
    size_t length;

    msgq_id = get_msgq_id(MSGQ_KEY);

    /* Message type */
    message.type = MSG_TYPE_HANDOUT;

    printf("Enter a message to add to message queue: ");
    if (scanf("%1023[^\n]", message.content.buffer) /* MESSAGE_SIZE - 1 */ != 1) {
        fprintf(stderr, "Empty message\n");
        exit(EXIT_FAILURE);
    }
    getchar();

    length = strlen(message.content.buffer) + 1;

    if (msgsnd(msgq_id, &message, length, IPC_NOWAIT) < 0) {
        perror("msgsnd()"); /* first, while errno is still the one of msgsnd() */
        fprintf(stderr, "%d, %ld, %s, %zu\n", msgq_id, message.type, message.content.buffer,
                length);
        exit(EXIT_FAILURE);
    } else {
        printf("Message sent\n");
    }

    return EXIT_SUCCESS;
}
posix_messages/include/macosx/logger.h

View on GitHub

#ifndef LOGGER_H
#define LOGGER_H

/**
 * \file logger.h
 *
 * Defines some logger functions.
 */

#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"

void log_error(const char *message, ...);

void log_info(const char *message, ...);

void log_debug(const char *message, ...);

#endif /* LOGGER_H */
posix_messages/include/macosx/mqueue-internal.h

View on GitHub

/**
 * @file mqueue-internal.h
 *
 * @author Stanislav Pankevich (https://github.com/stanislaw/posix-macos-addons)
 *
 * A message queue mechanism for MacOSX
 */

#ifndef _MQUEUE_INTERNAL_H_
#define _MQUEUE_INTERNAL_H_

#include <stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

extern const size_t MQ_FS_NAME_MAX;

int mq_get_fs_pathname(const char *const pathname, char *const out_pathname);

#ifdef __cplusplus
}
#endif

#endif /* _MQUEUE_INTERNAL_H_ */
posix_messages/include/macosx/mqueue.h

View on GitHub

/**
 * @file mqueue.h
 *
 * @author Stanislav Pankevich (https://github.com/stanislaw/posix-macos-addons)
 *
 * A message queue mechanism for macOS
 */

#ifndef _POSIX_MACOS_MQUEUE_H_
#define _POSIX_MACOS_MQUEUE_H_

#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>

#ifdef __cplusplus
extern "C" {
#endif

/* \todo: MacOS should have this defined */
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

/**
 * Opaque datatype.
 */
typedef struct mq_info *mqd_t;

struct mq_attr {
    long mq_flags;   /*!< Message queue flag: O_NONBLOCK */
    long mq_maxmsg;  /*!< Max number of messages allowed on queue */
    long mq_msgsize; /*!< Max size of a message (in bytes) */
    long mq_curmsgs; /*!< Number of messages currently on queue */
};

/**
 * One mq_hdr{} per queue, at beginning of mapped file.
 */
struct mq_hdr {
    struct mq_attr mqh_attr;   /*!< The queue's attributes */
    long mqh_head;             /*!< Index of the first message */
    long mqh_free;             /*!< Index of the first free message */
    long mqh_nwait;            /*!< #threads blocked in mq_receive() */
    pid_t mqh_pid;             /*!< Nonzero PID if mqh_event set */
    struct sigevent mqh_event; /*!< For mq_notify() */
    pthread_mutex_t mqh_lock;  /*!< Mutex lock */
    pthread_cond_t mqh_wait;   /*!< and condition variable */
};

/**
 * One mymsg_hdr{} at the front of each message in the mapped file.
 */
struct mymsg_hdr {
    long msg_next;   /*!< Index of next on linked list (must be first member in
                      struct). */
    ssize_t msg_len; /*!< Actual length */
    unsigned int msg_prio; /*!< Priority */
};

/**
 * One mq_info{} malloc'ed per process per mq_open().
 */
struct mq_info {
    struct mq_hdr *mqi_hdr; /*!< Start of mmap'ed region. */
    long mqi_magic;         /*!< Magic number if open */
    int mqi_flags;          /*!< Flags for this process */
};

#define MQI_MAGIC 0x98765432

/** Size of message in file is rounded up for alignment. */
#define MSGSIZE(i) ((((i) + sizeof(long) - 1) / sizeof(long)) * sizeof(long))

int mq_close(mqd_t);

int mq_getattr(mqd_t, struct mq_attr *);

int mq_notify(mqd_t, const struct sigevent *);

mqd_t mq_open(const char *, int, ...);

ssize_t mq_receive(mqd_t, char *, size_t, unsigned int *);

int mq_send(mqd_t, const char *, size_t, unsigned int);

int mq_setattr(mqd_t, const struct mq_attr *, struct mq_attr *);

int mq_unlink(const char *name);

int mq_timedsend(mqd_t mqdes, const char *msg_ptr, size_t msg_len,
                 unsigned msg_prio, const struct timespec *abs_timeout);

ssize_t mq_timedreceive(mqd_t mqdes, char *msg_ptr, size_t msg_len,
                        unsigned *msg_prio, const struct timespec *abs_timeout);

#ifdef __cplusplus
}
#endif

#endif /* _POSIX_MACOS_MQUEUE_H_ */
posix_messages/src/macosx_mqueue/logger.c

View on GitHub

#include "macosx/logger.h"

void log_format(const char *tag, const char *message, va_list args) {
    time_t now;
    time(&now);
    char *date = ctime(&now);
    date[strlen(date) - 1] = '\0';
    printf("%s [%s] ", date, tag);
    vprintf(message, args);
    printf("\n");
}

void log_error(const char *message, ...) {
    va_list args;
    va_start(args, message);
    printf(RED);
    log_format("Error", message, args);
    printf(RESET
    "");
    va_end(args);
}

void log_info(const char *message, ...) {
    va_list args;
    va_start(args, message);
    log_format("Info", message, args);
    va_end(args);
}

void log_debug(const char *message, ...) {
    va_list args;
    va_start(args, message);
    printf(CYN);
    log_format("Debug", message, args);
    printf(RESET
    "");
    va_end(args);
}
posix_messages/src/macosx_mqueue/mq_close.c

View on GitHub

#include "macosx/mqueue.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

int mq_close(mqd_t mqd) {
    long msgsize, filesize;
    struct mq_hdr *mqhdr;
    struct mq_attr *attr;
    struct mq_info *mqinfo;

    mqinfo = mqd;
    if (mqinfo->mqi_magic != MQI_MAGIC) {
        errno = EBADF;
        return (-1);
    }
    mqhdr = mqinfo->mqi_hdr;
    attr = &mqhdr->mqh_attr;

    if (mq_notify(mqd, NULL) != 0) /* unregister calling process */
        return (-1);

    msgsize = MSGSIZE(attr->mq_msgsize);
    filesize = sizeof(struct mq_hdr) +
               (attr->mq_maxmsg * (sizeof(struct mymsg_hdr) + msgsize));
    if (munmap(mqinfo->mqi_hdr, filesize) == -1)
        return (-1);

    mqinfo->mqi_magic = 0; /* just in case */
    free(mqinfo);
    return (0);
}
posix_messages/src/macosx_mqueue/mq_getattr.c

View on GitHub

#include "macosx/mqueue.h"

#include <errno.h>
#include <stdio.h>

int mq_getattr(mqd_t mqd, struct mq_attr *mqstat) {
    int n;
    struct mq_hdr *mqhdr;
    struct mq_attr *attr;
    struct mq_info *mqinfo;

    mqinfo = mqd;
    if (mqinfo->mqi_magic != MQI_MAGIC) {
        errno = EBADF;
        return (-1);
    }
    mqhdr = mqinfo->mqi_hdr;
    attr = &mqhdr->mqh_attr;
    if ((n = pthread_mutex_lock(&mqhdr->mqh_lock)) != 0) {
        errno = n;
        return (-1);
    }

    mqstat->mq_flags = mqinfo->mqi_flags; /* per-open */
    mqstat->mq_maxmsg = attr->mq_maxmsg;  /* remaining three per-queue */
    mqstat->mq_msgsize = attr->mq_msgsize;
    mqstat->mq_curmsgs = attr->mq_curmsgs;

    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return 0;
}
posix_messages/src/macosx_mqueue/mq_internal_fs.c

View on GitHub

#include "macosx/mqueue-internal.h"

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

const size_t MQ_FS_NAME_MAX = 64;

static const char prefix[] = "/tmp";

static const size_t MQ_NAME_MAX = 32;

static size_t safe_strlen(const char *str, size_t max_len) {
    const char *end = (const char *) memchr(str, '\0', max_len);
    if (end == NULL) {
        return max_len;
    } else {
        return end - str;
    }
}

int mq_get_fs_pathname(const char *const pathname, char *const out_pathname) {
    if (pathname[0] != '/') {
        return EINVAL;
    }

    size_t pathname_len = safe_strlen(pathname, MQ_NAME_MAX);
    if (pathname_len >= MQ_NAME_MAX) {
        return ENAMETOOLONG; /* user input: an error, not an assert() */
    }

    size_t internal_len =
            strlen(prefix) + pathname_len + 1; /* +1 for ending '\0' */
    assert(internal_len < MQ_FS_NAME_MAX);

    snprintf(out_pathname, internal_len, "%s%s", prefix, pathname);
    return 0;
}
posix_messages/src/macosx_mqueue/mq_notify.c

View on GitHub

#include "macosx/mqueue.h"

#include <errno.h>
#include <stdio.h>

int mq_notify(mqd_t mqd, const struct sigevent *notification) {
    int n;
    pid_t pid;
    struct mq_hdr *mqhdr;
    struct mq_info *mqinfo;

    mqinfo = mqd;
    if (mqinfo->mqi_magic != MQI_MAGIC) {
        errno = EBADF;
        return (-1);
    }
    mqhdr = mqinfo->mqi_hdr;
    if ((n = pthread_mutex_lock(&mqhdr->mqh_lock)) != 0) {
        errno = n;
        return (-1);
    }

    pid = getpid();
    if (notification == NULL) {
        if (mqhdr->mqh_pid == pid) {
            mqhdr->mqh_pid = 0; /* unregister calling process */
        }                     /* no error if caller not registered */
    } else {
        if (mqhdr->mqh_pid != 0) {
            if (kill(mqhdr->mqh_pid, 0) != -1 || errno != ESRCH) {
                errno = EBUSY;
                goto err;
            }
        }
        mqhdr->mqh_pid = pid;
        mqhdr->mqh_event = *notification;
    }
    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return 0;

    err:
    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return -1;
}
posix_messages/src/macosx_mqueue/mq_open.c

View on GitHub

#include "macosx/mqueue.h"

#include "macosx/mqueue-internal.h"

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>

#define MAX_TRIES 10 /* To wait for initialization */

/* TODO: CHECK THIS */
#define va_mode_t int

struct mq_attr defattr = {0, 128, 1024, 0};

mqd_t mq_open(const char *pathname, int oflag, ...) {
    int i, fd, nonblock, created, save_errno;
    long msgsize, filesize, index;
    va_list ap;
    mode_t mode;
    int8_t *mptr;
    struct stat statbuff;
    struct mq_hdr *mqhdr;
    struct mymsg_hdr *msghdr;
    struct mq_attr *attr;
    struct mq_info *mqinfo;
    pthread_mutexattr_t mattr;
    pthread_condattr_t cattr;

    created = 0;
    nonblock = oflag & O_NONBLOCK;
    oflag &= ~O_NONBLOCK;
    mptr = (int8_t *) MAP_FAILED;
    mqinfo = NULL;

    char fs_pathname[MQ_FS_NAME_MAX];
    if ((i = mq_get_fs_pathname(pathname, fs_pathname)) != 0) {
        errno = i; /* EINVAL or ENAMETOOLONG */
        return ((mqd_t) - 1);
    }

    again:
    if (oflag & O_CREAT) {
        va_start(ap, oflag); /* init ap to final named argument */
        mode = va_arg(ap,
        va_mode_t) &~S_IXUSR;
        attr = va_arg(ap,
        struct mq_attr *);
        va_end(ap);

        /* open and specify O_EXCL and user-execute; the access mode of the
         * caller (O_RDONLY, O_WRONLY) is replaced by O_RDWR: O_WRONLY | O_RDWR
         * is an invalid access mode (EINVAL) */
        fd = open(fs_pathname, (oflag & ~O_ACCMODE) | O_EXCL | O_RDWR,
                  mode | S_IXUSR);
        if (fd < 0) {
            if (errno == EEXIST && (oflag & O_EXCL) == 0)
                goto exists; /* already exists, OK */
            else
                return ((mqd_t) - 1);
        }
        created = 1;
        /* first one to create the file initializes it */
        if (attr == NULL)
            attr = &defattr;
        else {
            if (attr->mq_maxmsg <= 0 || attr->mq_msgsize <= 0) {
                errno = EINVAL;
                goto err;
            }
        }

        /* calculate and set the file size */
        msgsize = MSGSIZE(attr->mq_msgsize);
        filesize = sizeof(struct mq_hdr) +
                   (attr->mq_maxmsg * (sizeof(struct mymsg_hdr) + msgsize));
        if (lseek(fd, filesize - 1, SEEK_SET) == -1)
            goto err;
        if (write(fd, "", 1) == -1)
            goto err;

        /* memory map the file */
        mptr = mmap(NULL, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (mptr == MAP_FAILED)
            goto err;

        /* allocate one mq_info{} for the queue */
        /* *INDENT-OFF* */
        if ((mqinfo = malloc(sizeof(struct mq_info))) == NULL)
            goto err;
        /* *INDENT-ON* */
        mqinfo->mqi_hdr = mqhdr = (struct mq_hdr *) mptr;
        mqinfo->mqi_magic = MQI_MAGIC;
        mqinfo->mqi_flags = nonblock;

        /* initialize header at beginning of file */
        /* create free list with all messages on it */
        mqhdr->mqh_attr.mq_flags = 0;
        mqhdr->mqh_attr.mq_maxmsg = attr->mq_maxmsg;
        mqhdr->mqh_attr.mq_msgsize = attr->mq_msgsize;
        mqhdr->mqh_attr.mq_curmsgs = 0;
        mqhdr->mqh_nwait = 0;
        mqhdr->mqh_pid = 0;
        mqhdr->mqh_head = 0;
        index = sizeof(struct mq_hdr);
        mqhdr->mqh_free = index;
        for (i = 0; i < attr->mq_maxmsg - 1; i++) {
            msghdr = (struct mymsg_hdr *) &mptr[index];
            index += sizeof(struct mymsg_hdr) + msgsize;
            msghdr->msg_next = index;
        }
        msghdr = (struct mymsg_hdr *) &mptr[index];
        msghdr->msg_next = 0; /* end of free list */

        /* initialize mutex & condition variable */
        if ((i = pthread_mutexattr_init(&mattr)) != 0)
            goto pthreaderr;
        pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
        i = pthread_mutex_init(&mqhdr->mqh_lock, &mattr);
        pthread_mutexattr_destroy(&mattr); /* be sure to destroy */
        if (i != 0)
            goto pthreaderr;

        if ((i = pthread_condattr_init(&cattr)) != 0)
            goto pthreaderr;
        pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED);
        i = pthread_cond_init(&mqhdr->mqh_wait, &cattr);
        pthread_condattr_destroy(&cattr); /* be sure to destroy */
        if (i != 0)
            goto pthreaderr;

        /* initialization complete, turn off user-execute bit */
        if (fchmod(fd, mode) == -1)
            goto err;
        close(fd);
        return ((mqd_t) mqinfo);
    }

    exists:
    /* open the file then memory map */
    if ((fd = open(fs_pathname, O_RDWR)) < 0) {
        if (errno == ENOENT && (oflag & O_CREAT))
            goto again;
        goto err;
    }

    /* make certain initialization is complete */
    for (i = 0; i < MAX_TRIES; i++) {
        if (stat(fs_pathname, &statbuff) == -1) {
            if (errno == ENOENT && (oflag & O_CREAT)) {
                close(fd);
                goto again;
            }
            goto err;
        }
        if ((statbuff.st_mode & S_IXUSR) == 0)
            break;
        sleep(1);
    }
    if (i == MAX_TRIES) {
        errno = ETIMEDOUT;
        goto err;
    }

    filesize = statbuff.st_size;
    mptr = mmap(NULL, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (mptr == MAP_FAILED)
        goto err;
    close(fd);
    fd = -1; /* already closed: not closed again on error */

    /* allocate one mq_info{} for each open */
    if ((mqinfo = malloc(sizeof(struct mq_info))) == NULL)
        goto err;
    mqinfo->mqi_hdr = (struct mq_hdr *) mptr;
    mqinfo->mqi_magic = MQI_MAGIC;
    mqinfo->mqi_flags = nonblock;
    return ((mqd_t) mqinfo);

    pthreaderr:
    errno = i;

    err:
    /* don't let following function calls change errno */
    save_errno = errno;
    if (created)
        unlink(fs_pathname);
    if (mptr != MAP_FAILED)
        munmap(mptr, filesize);
    if (mqinfo != NULL)
        free(mqinfo);
    if (fd != -1)
        close(fd);
    errno = save_errno;
    return ((mqd_t) - 1);
}
posix_messages/src/macosx_mqueue/mq_receive.c

View on GitHub

#include "macosx/logger.h"
#include "macosx/mqueue.h"

#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

ssize_t mq_receive(mqd_t mqd, char *ptr, size_t maxlen, unsigned int *priop) {
    int n;
    long index;
    int8_t *mptr;
    ssize_t len;
    struct mq_hdr *mqhdr;
    struct mq_attr *attr;
    struct mymsg_hdr *msghdr;
    struct mq_info *mqinfo;

    mqinfo = mqd;
    if (mqinfo->mqi_magic != MQI_MAGIC) {
        errno = EBADF;
        return (-1);
    }
    mqhdr = mqinfo->mqi_hdr; /* struct pointer */
    mptr = (int8_t *) mqhdr;  /* byte pointer */
    attr = &mqhdr->mqh_attr;
    if ((n = pthread_mutex_lock(&mqhdr->mqh_lock)) != 0) {
        errno = n;
        return (-1);
    }

    if (maxlen < (size_t) attr->mq_msgsize) {
        errno = EMSGSIZE;
        goto err;
    }
    if (attr->mq_curmsgs == 0) { /* queue is empty */
        if (mqinfo->mqi_flags & O_NONBLOCK) {
            errno = EAGAIN;
            goto err;
        }
        /* wait for a message to be placed onto queue */
        mqhdr->mqh_nwait++;
        /* may return EINVAL at once between two processes on macOS (see
         * mq_timedreceive.c): the loop then polls actively */
        while (attr->mq_curmsgs == 0)
            pthread_cond_wait(&mqhdr->mqh_wait, &mqhdr->mqh_lock);
        mqhdr->mqh_nwait--;
    }

    if ((index = mqhdr->mqh_head) == 0) {
        log_info("mq_receive: curmsgs = %ld; head = 0\n", attr->mq_curmsgs);
    }

    msghdr = (struct mymsg_hdr *) &mptr[index];
    mqhdr->mqh_head = msghdr->msg_next; /* new head of list */
    len = msghdr->msg_len;
    memcpy(ptr, msghdr + 1, len); /* copy the message itself */
    if (priop != NULL)
        *priop = msghdr->msg_prio;

    /* just-read message goes to front of free list */
    msghdr->msg_next = mqhdr->mqh_free;
    mqhdr->mqh_free = index;

    /* wake up everyone blocked in mq_send waiting for room: signaling only
     * when the queue was full loses wake-ups with several blocked senders */
    pthread_cond_broadcast(&mqhdr->mqh_wait);
    attr->mq_curmsgs--;

    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return (len);

    err:
    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return (-1);
}
posix_messages/src/macosx_mqueue/mq_send.c

View on GitHub

#include "macosx/mqueue.h"

#include <assert.h>
#include <stdint.h>
#include <time.h>

int mq_send(mqd_t mqd, const char *ptr, size_t len, unsigned int prio) {
    assert(sizeof(((struct timespec *) 0)->tv_sec) == 8);

    struct timespec distant_future;
    distant_future.tv_nsec = 0;
    distant_future.tv_sec = (int64_t)(UINT64_MAX / 2);

    return mq_timedsend(mqd, ptr, len, prio, &distant_future);
}
posix_messages/src/macosx_mqueue/mq_setattr.c

View on GitHub

#include "macosx/mqueue.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>

int mq_setattr(mqd_t mqd, const struct mq_attr *mqstat,
               struct mq_attr *omqstat) {
    int n;
    struct mq_hdr *mqhdr;
    struct mq_attr *attr;
    struct mq_info *mqinfo;

    mqinfo = mqd;
    if (mqinfo->mqi_magic != MQI_MAGIC) {
        errno = EBADF;
        return (-1);
    }
    mqhdr = mqinfo->mqi_hdr;
    attr = &mqhdr->mqh_attr;
    if ((n = pthread_mutex_lock(&mqhdr->mqh_lock)) != 0) {
        errno = n;
        return (-1);
    }

    if (omqstat != NULL) {
        omqstat->mq_flags = mqinfo->mqi_flags; /* previous attributes */
        omqstat->mq_maxmsg = attr->mq_maxmsg;
        omqstat->mq_msgsize = attr->mq_msgsize;
        omqstat->mq_curmsgs = attr->mq_curmsgs; /* and current status */
    }

    if (mqstat->mq_flags & O_NONBLOCK)
        mqinfo->mqi_flags |= O_NONBLOCK;
    else
        mqinfo->mqi_flags &= ~O_NONBLOCK;

    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return (0);
}
posix_messages/src/macosx_mqueue/mq_timedreceive.c

View on GitHub

#include "macosx/logger.h"
#include "macosx/mqueue.h"

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/file.h>

ssize_t mq_timedreceive(mqd_t mqd, char *ptr, size_t maxlen, unsigned *priop,
                        const struct timespec *abs_timeout) {
    int n;
    long index;
    int8_t *mptr;
    ssize_t len;
    struct mq_hdr *mqhdr;
    struct mq_attr *attr;
    struct mymsg_hdr *msghdr;
    struct mq_info *mqinfo;

    mqinfo = mqd;
    if (mqinfo->mqi_magic != MQI_MAGIC) {
        errno = EBADF;
        return (-1);
    }
    mqhdr = mqinfo->mqi_hdr; /* struct pointer */
    mptr = (int8_t *) mqhdr;  /* byte pointer */
    attr = &mqhdr->mqh_attr;
    if ((n = pthread_mutex_lock(&mqhdr->mqh_lock)) != 0) {
        errno = n;
        return (-1);
    }

    if (maxlen < (size_t) attr->mq_msgsize) {
        errno = EMSGSIZE;
        goto err;
    }
    if (attr->mq_curmsgs == 0) { /* queue is empty */
        if (mqinfo->mqi_flags & O_NONBLOCK) {
            errno = EAGAIN;
            goto err;
        }
        /* wait for a message to be placed onto queue */
        mqhdr->mqh_nwait++;
        while (attr->mq_curmsgs == 0) {
            int wait_result = pthread_cond_timedwait(&mqhdr->mqh_wait,
                                                     &mqhdr->mqh_lock,
                                                     abs_timeout);
            /* Only ETIMEDOUT ends the wait. On macOS, a process-shared
             * condition variable waited on from two processes that map the
             * queue at different addresses returns EINVAL at once: the wait
             * then degrades into active polling, but remains correct. */
            if (wait_result == ETIMEDOUT) {
                mqhdr->mqh_nwait--; /* no longer waiting */
                errno = ETIMEDOUT;
                goto err;
            }
        }
        mqhdr->mqh_nwait--;
    }

    if ((index = mqhdr->mqh_head) == 0) {
        log_info("mq_receive: curmsgs = %ld; head = 0\n", attr->mq_curmsgs);
    }

    msghdr = (struct mymsg_hdr *) &mptr[index];
    mqhdr->mqh_head = msghdr->msg_next; /* new head of list */
    len = msghdr->msg_len;
    memcpy(ptr, msghdr + 1, len); /* copy the message itself */
    if (priop != NULL)
        *priop = msghdr->msg_prio;

    /* just-read message goes to front of free list */
    msghdr->msg_next = mqhdr->mqh_free;
    mqhdr->mqh_free = index;

    /* wake up everyone blocked in mq_send waiting for room: signaling only
     * when the queue was full loses wake-ups with several blocked senders.
     * (no assert() around these calls: compiled out with NDEBUG) */
    pthread_cond_broadcast(&mqhdr->mqh_wait);
    attr->mq_curmsgs--;

    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return (len);

    err:
    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return (-1);
}
posix_messages/src/macosx_mqueue/mq_timedsend.c

View on GitHub

#include "macosx/logger.h"
#include "macosx/mqueue.h"

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/file.h>

int mq_timedsend(mqd_t mqd, const char *ptr, size_t len, unsigned prio,
                 const struct timespec *abs_timeout) {
    int n;
    long index;
    long freeindex;
    int8_t *mptr;
    struct sigevent *sigev;
    struct mq_hdr *mqhdr;
    struct mq_attr *attr;
    struct mymsg_hdr *msghdr;
    struct mymsg_hdr *nmsghdr;
    struct mymsg_hdr *pmsghdr;
    struct mq_info *mqinfo;

    mqinfo = mqd;
    if (mqinfo->mqi_magic != MQI_MAGIC) {
        errno = EBADF;
        return -1;
    }
    mqhdr = mqinfo->mqi_hdr; /* struct pointer */
    mptr = (int8_t *) mqhdr;  /* byte pointer */
    attr = &mqhdr->mqh_attr;
    if ((n = pthread_mutex_lock(&mqhdr->mqh_lock)) != 0) {
        errno = n;
        return -1;
    }

    if (len > (size_t) attr->mq_msgsize) {
        errno = EMSGSIZE;
        goto err;
    }
    if (attr->mq_curmsgs == 0) {
        if (mqhdr->mqh_pid != 0 && mqhdr->mqh_nwait == 0) {
            sigev = &mqhdr->mqh_event;
            if (sigev->sigev_notify == SIGEV_SIGNAL) {
                /* sigqueue does not exit on macOS, but it looks like it is
                 * enough if we just send a signal with kill to make simple
                 * tests pass. If a user does not use mq_notify this can be
                 * considered an unused branch.
                 * sigqueue(mqhdr->mqh_pid, sigev->sigev_signo, sigev->sigev_value);
                 */
                kill(mqhdr->mqh_pid, sigev->sigev_signo);
            }
            mqhdr->mqh_pid = 0; /* unregister */
        }
    } else if (attr->mq_curmsgs >= attr->mq_maxmsg) {
        /* queue is full */
        if (mqinfo->mqi_flags & O_NONBLOCK) {
            errno = EAGAIN;
            goto err;
        }
        /* wait for room for one message on the queue */
        while (attr->mq_curmsgs >= attr->mq_maxmsg) {
            int wait_result = pthread_cond_timedwait(&mqhdr->mqh_wait,
                                                     &mqhdr->mqh_lock,
                                                     abs_timeout);

            /* Only ETIMEDOUT ends the wait. On macOS, a process-shared
             * condition variable waited on from two processes that map the
             * queue at different addresses returns EINVAL at once: the wait
             * then degrades into active polling, but remains correct. */
            if (wait_result == ETIMEDOUT) {
                errno = ETIMEDOUT;
                goto err;
            }
        }
    }

    /* nmsghdr will point to new message */
    if ((freeindex = mqhdr->mqh_free) == 0) {
        log_info("mq_send: curmsgs = %ld; free = 0\n", attr->mq_curmsgs);
    }
    nmsghdr = (struct mymsg_hdr *) &mptr[freeindex];
    nmsghdr->msg_prio = prio;
    nmsghdr->msg_len = len;
    memcpy(nmsghdr + 1, ptr, len);       /* copy message from caller */
    mqhdr->mqh_free = nmsghdr->msg_next; /* new freelist head */

    /* find right place for message in linked list */
    index = mqhdr->mqh_head;
    pmsghdr = (struct mymsg_hdr *) &(mqhdr->mqh_head);
    while (index != 0) {
        msghdr = (struct mymsg_hdr *) &mptr[index];
        if (prio > msghdr->msg_prio) {
            nmsghdr->msg_next = index;
            pmsghdr->msg_next = freeindex;
            break;
        }
        index = msghdr->msg_next;
        pmsghdr = msghdr;
    }
    if (index == 0) {
        /* queue was empty or new goes at end of list */
        pmsghdr->msg_next = freeindex;
        nmsghdr->msg_next = 0;
    }
    /* wake up everyone blocked in mq_receive waiting for a message: signaling
     * only when the queue was empty loses wake-ups with several receivers */
    pthread_cond_broadcast(&mqhdr->mqh_wait);
    attr->mq_curmsgs++;

    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return 0;

    err:
    pthread_mutex_unlock(&mqhdr->mqh_lock);
    return -1;
}
posix_messages/src/macosx_mqueue/mq_unlink.c

View on GitHub

#include "macosx/mqueue-internal.h"
#include "macosx/mqueue.h"

#include <errno.h>

int mq_unlink(const char *pathname) {
    char fs_pathname[MQ_FS_NAME_MAX];
    int n;

    if ((n = mq_get_fs_pathname(pathname, fs_pathname)) != 0) {
        errno = n; /* EINVAL or ENAMETOOLONG */
        return -1;
    }
    if (unlink(fs_pathname) == -1) {
        return -1;
    }
    return 0;
}