Aller au contenu

Exemples de multiplexage des entrées-sorties

Cette section contient des exemples illustrant le multiplexage des entrées-sorties avec select() et poll(). Ces appels système permettent à un processus de surveiller simultanément plusieurs descripteurs de fichiers, en se bloquant jusqu'à ce qu'au moins l'un d'eux soit prêt pour une entrée-sortie ou qu'un délai d'attente expire. Ce schéma est fondamental pour les serveurs qui gèrent plusieurs clients et pour tout programme qui doit réagir à des événements provenant de plusieurs sources sans se bloquer.

select()

select() surveille trois ensembles de descripteurs de fichiers (lecture, écriture, exception), représentés par des masques de bits fd_set. Il est limité à FD_SETSIZE descripteurs (généralement 1024) et impose de reconstruire les ensembles de descripteurs avant chaque appel.

Fichier Description Lien
select_01.c Surveille stdin avec un délai d'attente de 5 secondes : renvoie l'entrée en écho ou signale l'expiration du délai si aucune donnée n'arrive Voir
select_02.c Surveille simultanément deux tubes anonymes : lit les données de l'enfant qui écrit en premier, sans se bloquer sur l'autre Voir
pipes_terminal_sequential.c Exemple fil rouge, version 1 : lit deux tubes et le terminal l'un après l'autre ; un read() bloquant retarde les autres sources (cours, chapitre "Multiplexage des entrées/sorties") Voir
pipes_terminal_select.c Exemple fil rouge, version 2 : lit deux tubes et le terminal avec select(), en reconstruisant le fd_set à chaque tour et en retirant les sources arrivées à EOF (cours, chapitre "Multiplexage des entrées/sorties") Voir

poll()

poll() prend un tableau de descripteurs struct pollfd. Il n'a pas de limite FD_SETSIZE, n'impose pas de reconstruire l'ensemble de descripteurs à chaque appel et permet de retirer un descripteur en positionnant .fd = -1.

Fichier Description Lien
poll_01.c Même comportement que select_01.c, mais avec poll() : comparer les deux API côte à côte Voir
poll_02.c Même comportement que select_02.c, mais avec poll() : montre le tableau pollfd stable et l'idiome de retrait par .fd = -1 Voir
pipes_terminal_poll.c Exemple fil rouge, version 3 : identique à pipes_terminal_select.c avec poll() ; traitement de POLLERR/POLLNVAL et retrait par .fd = -1 (cours, chapitre "Multiplexage des entrées/sorties") Voir

Code source

src/pipes_terminal_poll.c

Voir sur GitHub

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

/**
 * @file pipes_terminal_poll.c
 * @brief Running example, version 3: reads two pipes and the terminal with
 * poll().
 *
 * Lecture: chapter os-07 "Multiplexage des entrées/sorties"
 * (running example "Version 3 - poll()").
 *
 * Same scenario as pipes_terminal_select.c: two children write 5 messages
 * each into their own pipe (A every 3 seconds, B every second) and the
 * parent copies each message as soon as it arrives, as well as the lines
 * typed on the terminal.
 *
 * Key points:
 *   - the pollfd array is filled only once, before the loop: the kernel
 *     only modifies revents;
 *   - no computation of the highest descriptor;
 *   - an entry whose fd is negative is ignored: this is how a source at
 *     EOF (or in POLLERR / POLLNVAL) is removed.
 *
 * \code{.bash}
 *   $ ./pipes_terminal_poll
 *   [B] message 1
 *   [B] message 2
 *   [A] message 1
 *   ...
 * \endcode
 */

#define NB 3

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

/**
 * @brief Child code: writes 5 messages into the pipe, one every 'delai'
 * seconds, then terminates.
 */
void producteur(int tube[2], const char *nom, int delai) {
    close(tube[0]);          /* child: writer */
    for (int i = 1; i <= 5; i++) {
        sleep(delai);
        dprintf(tube[1], "[%s] message %d\n", nom, i);
    }
    exit(EXIT_SUCCESS);      /* closes tube[1] */
}

/**
 * @brief Reads fd once and copies what was read to the standard output.
 * @return 0 on EOF, -1 on error, otherwise the number of bytes read.
 */
ssize_t copier(int fd) {
    char buf[256];
    ssize_t n = read(fd, buf, sizeof buf);
    if (n > 0) {
        if (write(STDOUT_FILENO, buf, n) == -1) {
            return -1;
        }
    }
    return n;
}

int main(void) {
    int tube_a[2], tube_b[2];
    pid_t pid;

    if (pipe(tube_a) == -1) {
        handle_fatal_error_and_exit("pipe");
    }
    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }
    if (pid == 0) {
        producteur(tube_a, "A", 3);   /* does not return */
    }
    close(tube_a[1]);                 /* parent: reader */

    if (pipe(tube_b) == -1) {
        handle_fatal_error_and_exit("pipe");
    }
    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }
    if (pid == 0) {
        producteur(tube_b, "B", 1);
    }
    close(tube_b[1]);

    struct pollfd fds[NB] = {
        { .fd = tube_a[0],    .events = POLLIN, .revents = 0 },
        { .fd = tube_b[0],    .events = POLLIN, .revents = 0 },
        { .fd = STDIN_FILENO, .events = POLLIN, .revents = 0 },
    };
    int ouverts = NB;                 /* sources still open */

    while (ouverts > 0) {
        if (poll(fds, NB, -1) == -1) {    /* -1: infinite */
            if (errno == EINTR) {
                continue;             /* signal received: resume */
            }
            perror("poll");
            break;
        }
        for (int i = 0; i < NB; i++) {
            short ev = fds[i].revents;
            if (ev == 0) {
                continue;
            }
            /* POLLERR, POLLNVAL: unusable fd */
            if ((ev & (POLLERR | POLLNVAL))
                || copier(fds[i].fd) <= 0) {  /* EOF, error */
                close(fds[i].fd);
                fds[i].fd = -1;           /* ignored by poll() */
                ouverts--;
            }
        }
    }

    wait(NULL);
    wait(NULL);

    return EXIT_SUCCESS;
}
src/pipes_terminal_select.c

Voir sur GitHub

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

/**
 * @file pipes_terminal_select.c
 * @brief Running example, version 2: reads two pipes and the terminal with
 * select().
 *
 * Lecture: chapter os-07 "Multiplexage des entrées/sorties"
 * (running example "Version 2 - select()").
 *
 * Two children write 5 messages each into their own pipe (child A every
 * 3 seconds, child B every second). The parent waits for the three sources
 * (pipe of A, pipe of B, terminal) with a single select() call and copies
 * each message as soon as it arrives, whatever its source.
 *
 * Key points:
 *   - the fd_set is modified by select(): it is rebuilt before each call,
 *     as is nfds (highest descriptor + 1);
 *   - a descriptor at EOF is always ready: it is closed and removed (-1),
 *     otherwise the loop would become a busy loop;
 *   - the program ends when A and B have finished and Ctrl-D is typed.
 *
 * \code{.bash}
 *   $ ./pipes_terminal_select
 *   [B] message 1
 *   [B] message 2
 *   [A] message 1
 *   [B] message 3
 *   bonjour
 *   bonjour
 *   ...
 * \endcode
 */

#define NB 3

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

/**
 * @brief Child code: writes 5 messages into the pipe, one every 'delai'
 * seconds, then terminates.
 */
void producteur(int tube[2], const char *nom, int delai) {
    close(tube[0]);          /* child: writer */
    for (int i = 1; i <= 5; i++) {
        sleep(delai);
        dprintf(tube[1], "[%s] message %d\n", nom, i);
    }
    exit(EXIT_SUCCESS);      /* closes tube[1] */
}

/**
 * @brief Reads fd once and copies what was read to the standard output.
 * @return 0 on EOF, -1 on error, otherwise the number of bytes read.
 */
ssize_t copier(int fd) {
    char buf[256];
    ssize_t n = read(fd, buf, sizeof buf);
    if (n > 0) {
        if (write(STDOUT_FILENO, buf, n) == -1) {
            return -1;
        }
    }
    return n;
}

/**
 * @brief Rebuilds the set of descriptors to watch.
 * @return The highest descriptor of the set (-1 if the set is empty).
 */
int preparer(fd_set *rfds, const int fds[]) {
    int max = -1;
    FD_ZERO(rfds);
    for (int i = 0; i < NB; i++) {
        if (fds[i] != -1) {          /* -1: removed */
            FD_SET(fds[i], rfds);
            if (fds[i] > max) {
                max = fds[i];
            }
        }
    }
    return max;
}

int main(void) {
    int tube_a[2], tube_b[2];
    pid_t pid;

    if (pipe(tube_a) == -1) {
        handle_fatal_error_and_exit("pipe");
    }
    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }
    if (pid == 0) {
        producteur(tube_a, "A", 3);   /* does not return */
    }
    close(tube_a[1]);                 /* parent: reader */

    if (pipe(tube_b) == -1) {
        handle_fatal_error_and_exit("pipe");
    }
    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }
    if (pid == 0) {
        producteur(tube_b, "B", 1);
    }
    close(tube_b[1]);

    int fds[NB] = { tube_a[0], tube_b[0], STDIN_FILENO };
    int ouverts = NB;                 /* sources still open */

    while (ouverts > 0) {
        fd_set rfds;
        int max = preparer(&rfds, fds);   /* at each iteration */
        if (select(max + 1, &rfds, NULL, NULL, NULL) == -1) {
            if (errno == EINTR) {
                continue;             /* signal received: resume */
            }
            perror("select");
            break;
        }
        for (int i = 0; i < NB; i++) {
            if (fds[i] == -1 || !FD_ISSET(fds[i], &rfds)) {
                continue;
            }
            if (copier(fds[i]) <= 0) {    /* EOF or error */
                close(fds[i]);
                fds[i] = -1;              /* removal */
                ouverts--;
            }
        }
    }

    wait(NULL);
    wait(NULL);

    return EXIT_SUCCESS;
}
src/pipes_terminal_sequential.c

Voir sur GitHub

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

/**
 * @file pipes_terminal_sequential.c
 * @brief Running example, version 1: reads two pipes and the terminal one
 * after the other (sequential reading, no multiplexing).
 *
 * Lecture: chapter os-07 "Multiplexage des entrées/sorties"
 * (running example "Version 1 - lecture séquentielle").
 *
 * Two children write 5 messages each into their own pipe (child A every
 * 3 seconds, child B every second). The parent copies each source in turn
 * to the standard output: the pipe of A, the pipe of B, then the terminal.
 *
 * Key points:
 *   - each read() blocks: as long as the user types nothing, neither A nor
 *     B is displayed, even if their data is already waiting in the pipes;
 *   - the display order is imposed by the code, not by the arrivals.
 *
 * Compare with pipes_terminal_select.c and pipes_terminal_poll.c.
 *
 * \code{.bash}
 *   $ ./pipes_terminal_sequential
 *   [A] message 1
 *   [B] message 1
 *   [B] message 2
 *   (nothing more until Enter is pressed)
 * \endcode
 */

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

/**
 * @brief Child code: writes 5 messages into the pipe, one every 'delai'
 * seconds, then terminates.
 */
void producteur(int tube[2], const char *nom, int delai) {
    close(tube[0]);          /* child: writer */
    for (int i = 1; i <= 5; i++) {
        sleep(delai);
        dprintf(tube[1], "[%s] message %d\n", nom, i);
    }
    exit(EXIT_SUCCESS);      /* closes tube[1] */
}

/**
 * @brief Reads fd once and copies what was read to the standard output.
 * @return 0 on EOF, -1 on error, otherwise the number of bytes read.
 */
ssize_t copier(int fd) {
    char buf[256];
    ssize_t n = read(fd, buf, sizeof buf);
    if (n > 0) {
        if (write(STDOUT_FILENO, buf, n) == -1) {
            return -1;
        }
    }
    return n;
}

int main(void) {
    int tube_a[2], tube_b[2];
    pid_t pid;

    /* Each pipe is created just before its fork(): B does not inherit
       the writer of A */
    if (pipe(tube_a) == -1) {
        handle_fatal_error_and_exit("pipe");
    }
    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }
    if (pid == 0) {
        producteur(tube_a, "A", 3);   /* does not return */
    }
    close(tube_a[1]);                 /* parent: reader */

    if (pipe(tube_b) == -1) {
        handle_fatal_error_and_exit("pipe");
    }
    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }
    if (pid == 0) {
        producteur(tube_b, "B", 1);
    }
    close(tube_b[1]);

    for (;;) {                        /* each in turn */
        ssize_t a = copier(tube_a[0]);    /* blocks up to 3 s */
        ssize_t b = copier(tube_b[0]);    /* B waits for its turn */
        ssize_t t = copier(STDIN_FILENO); /* blocks until Enter */
        if (a <= 0 && b <= 0 && t <= 0) {
            break;                    /* all three sources are closed */
        }
    }

    close(tube_a[0]);
    close(tube_b[0]);
    wait(NULL);
    wait(NULL);

    return EXIT_SUCCESS;
}
src/poll_01.c

Voir sur GitHub

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

#include <unistd.h>  /* read(), STDIN_FILENO */
#include <stdio.h>   /* printf(), fflush() */
#include <stdlib.h>  /* exit() */
#include <poll.h>    /* poll(), struct pollfd, POLLIN */

/**
 * @file poll_01.c
 * @brief Demonstrates poll() with a timeout on standard input.
 *
 * poll() is a modern alternative to select(). Instead of three fd_set
 * bitmasks it takes an array of struct pollfd, which scales better to
 * large numbers of descriptors and has a cleaner API.
 *
 * Compare with select_01.c: same behaviour, different API.
 * Key differences from select():
 *   - Timeout is a single integer in milliseconds (no struct timeval).
 *   - No need to rebuild the descriptor set before each call.
 *   - Not limited by FD_SETSIZE.
 *
 * \code{.bash}
 *   $ ./poll_01
 *   Waiting up to 5 seconds for input on stdin...
 *   hello
 *   You typed: hello
 *
 *   $ ./poll_01         (no input within 5 seconds)
 *   Waiting up to 5 seconds for input on stdin...
 *   Timeout: no input received.
 * \endcode
 */

#define TIMEOUT_MS  5000
#define BUFFER_SIZE 128

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

int main(void) {
    struct pollfd fds[1];
    char buffer[BUFFER_SIZE];
    int ready;
    ssize_t n;

    printf("Waiting up to %d seconds for input on stdin...\n", TIMEOUT_MS / 1000);
    fflush(stdout);

    fds[0].fd     = STDIN_FILENO;
    fds[0].events = POLLIN; /* Watch for data available to read */

    ready = poll(fds, 1, TIMEOUT_MS);
    if (ready == -1) {
        handle_fatal_error_and_exit("poll");
    }

    if (ready == 0) {
        printf("Timeout: no input received.\n");
        return EXIT_SUCCESS;
    }

    if (fds[0].revents & POLLIN) {
        n = read(STDIN_FILENO, buffer, sizeof(buffer) - 1);
        if (n == -1) {
            handle_fatal_error_and_exit("read");
        }
        buffer[n] = '\0';
        printf("You typed: %s", buffer);
    } else if (fds[0].revents & (POLLHUP | POLLERR | POLLNVAL)) {
        printf("Standard input is closed or invalid: nothing to read.\n");
    }

    return EXIT_SUCCESS;
}
src/poll_02.c

Voir sur GitHub

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

/**
 * @file poll_02.c
 * @brief Demonstrates poll() monitoring two pipes simultaneously.
 *
 * Functionally identical to select_02.c but uses poll(). Key differences
 * from the select() version:
 *   - No fd_set rebuild: the pollfd array is stable across iterations.
 *   - Removing a descriptor from monitoring is done by setting .fd = -1;
 *     poll() then skips that entry.
 *   - Scales to many descriptors without the FD_SETSIZE limit of select().
 *
 * \code{.bash}
 *   $ ./poll_02
 *   Ready: pipe 0 - message: "Data from child 1"
 *   Ready: pipe 1 - message: "Data from child 2"
 * \endcode
 */

#define BUFFER_SIZE 128
#define NUM_PIPES   2

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

int main(void) {
    int pipes[NUM_PIPES][2];
    struct pollfd fds[NUM_PIPES];
    char buffer[BUFFER_SIZE];
    int i, j, ready, done;
    ssize_t n;
    pid_t pid;

    for (i = 0; i < NUM_PIPES; i++) {
        if (pipe(pipes[i]) == -1) {
            handle_fatal_error_and_exit("pipe");
        }
    }

    /* Child i writes to pipe i after (i+1) seconds */
    for (i = 0; i < NUM_PIPES; i++) {
        pid = fork();
        if (pid == -1) {
            handle_fatal_error_and_exit("fork");
        }
        if (pid == 0) {
            for (j = 0; j < NUM_PIPES; j++) {
                close(pipes[j][0]);
                if (j != i) close(pipes[j][1]);
            }
            sleep(i + 1);
            if (dprintf(pipes[i][1], "Data from child %d", i + 1) == -1) {
                handle_fatal_error_and_exit("dprintf");
            }
            close(pipes[i][1]);
            exit(EXIT_SUCCESS);
        }
    }

    /* Parent: close write-ends, set up pollfd array */
    for (i = 0; i < NUM_PIPES; i++) {
        close(pipes[i][1]);
        fds[i].fd     = pipes[i][0];
        fds[i].events = POLLIN;
    }

    done = 0;
    while (done < NUM_PIPES) {
        ready = poll(fds, NUM_PIPES, -1); /* -1 = no timeout */
        if (ready == -1) {
            handle_fatal_error_and_exit("poll");
        }

        for (i = 0; i < NUM_PIPES; i++) {
            if (fds[i].fd == -1) {
                continue;
            }
            /* Error on the descriptor: removed without reading */
            if (fds[i].revents & (POLLERR | POLLNVAL)) {
                close(fds[i].fd);
                fds[i].fd = -1;
                done++;
                continue;
            }
            /* POLLHUP (child gone) may be set without POLLIN: read() then
             * returns 0 (EOF) and the pipe is removed as well, otherwise
             * poll() would return at once forever */
            if (!(fds[i].revents & (POLLIN | POLLHUP))) {
                continue;
            }
            n = read(fds[i].fd, buffer, sizeof(buffer) - 1);
            if (n == -1) {
                handle_fatal_error_and_exit("read");
            }
            buffer[n] = '\0';
            printf("Ready: pipe %d - message: \"%s\"\n", i, buffer);
            close(fds[i].fd);
            fds[i].fd = -1; /* Remove from future poll() calls */
            done++;
        }
    }

    for (i = 0; i < NUM_PIPES; i++) {
        wait(NULL);
    }

    return EXIT_SUCCESS;
}
src/select_01.c

Voir sur GitHub

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

#include <unistd.h>     /* read(), STDIN_FILENO */
#include <stdio.h>      /* printf(), fflush() */
#include <stdlib.h>     /* exit() */
#include <sys/select.h> /* select(), fd_set, FD_ZERO, FD_SET, FD_ISSET */
#include <sys/time.h>   /* struct timeval */

/**
 * @file select_01.c
 * @brief Demonstrates select() with a timeout on standard input.
 *
 * select() watches a set of file descriptors, blocking until at least one
 * becomes ready for I/O or a timeout expires. Here it monitors stdin for
 * up to 5 seconds. If the user types within that window the input is echoed;
 * otherwise a timeout message is printed.
 *
 * \code{.bash}
 *   $ ./select_01
 *   Waiting up to 5 seconds for input on stdin...
 *   hello
 *   You typed: hello
 *
 *   $ ./select_01         (no input within 5 seconds)
 *   Waiting up to 5 seconds for input on stdin...
 *   Timeout: no input received.
 * \endcode
 */

#define TIMEOUT_SECONDS 5
#define BUFFER_SIZE     128

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

int main(void) {
    fd_set readfds;
    struct timeval timeout;
    char buffer[BUFFER_SIZE];
    int ready;
    ssize_t n;

    printf("Waiting up to %d seconds for input on stdin...\n", TIMEOUT_SECONDS);
    fflush(stdout);

    FD_ZERO(&readfds);
    FD_SET(STDIN_FILENO, &readfds);

    /* select() may modify timeout: reinitialise before each call */
    timeout.tv_sec  = TIMEOUT_SECONDS;
    timeout.tv_usec = 0;

    ready = select(STDIN_FILENO + 1, &readfds, NULL, NULL, &timeout);
    if (ready == -1) {
        handle_fatal_error_and_exit("select");
    }

    if (ready == 0) {
        printf("Timeout: no input received.\n");
        return EXIT_SUCCESS;
    }

    /* STDIN_FILENO is ready for reading */
    n = read(STDIN_FILENO, buffer, sizeof(buffer) - 1);
    if (n == -1) {
        handle_fatal_error_and_exit("read");
    }
    buffer[n] = '\0';
    printf("You typed: %s", buffer);

    return EXIT_SUCCESS;
}
src/select_02.c

Voir sur GitHub

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

#include <unistd.h>     /* pipe(), fork(), read(), close(), write() */
#include <stdio.h>      /* printf() */
#include <stdlib.h>     /* exit() */
#include <sys/select.h> /* select(), fd_set, FD_ZERO, FD_SET, FD_ISSET */
#include <sys/time.h>   /* struct timeval */
#include <sys/wait.h>   /* wait() */

/**
 * @file select_02.c
 * @brief Demonstrates select() monitoring two pipes simultaneously.
 *
 * Two child processes each write a message to their own pipe after a
 * different delay. The parent uses select() to read from whichever pipe
 * becomes ready first, without blocking on the slower one.
 *
 * Key points:
 *   - fd_set and nfds must be rebuilt before each select() call.
 *   - The loop ends once both pipes have been drained.
 *
 * This pattern is fundamental for servers handling multiple clients.
 *
 * \code{.bash}
 *   $ ./select_02
 *   Ready: pipe from child 1 - message: "Data from child 1"
 *   Ready: pipe from child 2 - message: "Data from child 2"
 * \endcode
 */

#define BUFFER_SIZE 128

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

int main(void) {
    int pipe1[2], pipe2[2];
    fd_set readfds;
    char buffer[BUFFER_SIZE];
    int nfds, ready, done;
    ssize_t n;
    pid_t pid;

    if (pipe(pipe1) == -1 || pipe(pipe2) == -1) {
        handle_fatal_error_and_exit("pipe");
    }

    /* Child 1: writes after 1 second */
    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }
    if (pid == 0) {
        close(pipe1[0]); close(pipe2[0]); close(pipe2[1]);
        sleep(1);
        if (write(pipe1[1], "Data from child 1", 17) == -1) {
            handle_fatal_error_and_exit("write");
        }
        close(pipe1[1]);
        exit(EXIT_SUCCESS);
    }

    /* Child 2: writes after 2 seconds */
    pid = fork();
    if (pid == -1) {
        handle_fatal_error_and_exit("fork");
    }
    if (pid == 0) {
        close(pipe2[0]); close(pipe1[0]); close(pipe1[1]);
        sleep(2);
        if (write(pipe2[1], "Data from child 2", 17) == -1) {
            handle_fatal_error_and_exit("write");
        }
        close(pipe2[1]);
        exit(EXIT_SUCCESS);
    }

    /* Parent: close write-ends */
    close(pipe1[1]);
    close(pipe2[1]);

    done = 0;

    while (done < 2) {
        /* Rebuild fd_set and nfds before every select() call: a closed
           pipe (set to -1) is no longer watched */
        FD_ZERO(&readfds);
        nfds = 0;
        if (pipe1[0] != -1) {
            FD_SET(pipe1[0], &readfds);
            if (pipe1[0] + 1 > nfds) nfds = pipe1[0] + 1;
        }
        if (pipe2[0] != -1) {
            FD_SET(pipe2[0], &readfds);
            if (pipe2[0] + 1 > nfds) nfds = pipe2[0] + 1;
        }

        ready = select(nfds, &readfds, NULL, NULL, NULL);
        if (ready == -1) {
            handle_fatal_error_and_exit("select");
        }

        if (pipe1[0] != -1 && FD_ISSET(pipe1[0], &readfds)) {
            n = read(pipe1[0], buffer, sizeof(buffer) - 1);
            if (n == -1) {
                handle_fatal_error_and_exit("read");
            }
            buffer[n] = '\0';
            printf("Ready: pipe from child 1 - message: \"%s\"\n", buffer);
            close(pipe1[0]);
            pipe1[0] = -1;
            done++;
        }
        if (pipe2[0] != -1 && FD_ISSET(pipe2[0], &readfds)) {
            n = read(pipe2[0], buffer, sizeof(buffer) - 1);
            if (n == -1) {
                handle_fatal_error_and_exit("read");
            }
            buffer[n] = '\0';
            printf("Ready: pipe from child 2 - message: \"%s\"\n", buffer);
            close(pipe2[0]);
            pipe2[0] = -1;
            done++;
        }
    }

    wait(NULL);
    wait(NULL);

    return EXIT_SUCCESS;
}