CS 326 Operating Systems

pipe.c

DownloadView Raw

/**
 * pipe.c
 *
 * Demonstrates using pipes for IPC.
 *
 * Compile: gcc -g -Wall pipe.c -o pipe
 * Run: ./pipe
 */

#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {

    /* Creates a pipe. */
    int fd[2];
    if (pipe(fd) == -1) {
        perror("pipe");
        return EXIT_FAILURE;
    }

    pid_t pid = fork();
    if (pid == 0) {
        /* Child */
        close(fd[1]);
        dup2(fd[0], STDIN_FILENO);
        char buf[100];
        while (true) {
            fgets(buf, 100, stdin);
            /* Print out what we've received. */
            printf("Got -> %s", buf);

            /* We sleep here to slow things down... but what is happening behind
             * the scenes? */
            sleep(1);
        }
        close(fd[0]);
    } else {
        /* Parent */
        close(fd[0]);
        dup2(fd[1], STDOUT_FILENO);
        while(true) {
            int r = rand();
            printf("Random number: %d\n", r);
        }
        close(fd[1]);
    }

    return 0;
}