Skip to content
Advertisement

Unix pipe experiment hangs

The problem is that this program won’t output the expected START and END, also not exiting unless I kill it from shell.

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

void check(bool b, const char *cp) {
    if (!b) {
        perror(cp);
        exit(EXIT_FAILURE);
    }
}

int main(void) {
    int fd[2];
    check(pipe(fd) != -1, "pipe");
    pid_t pid = fork();
    check(pid != -1, "fork");
    if (pid == 0) {
        check(dup2(1, fd[1]) != -1, "dup2");
        check(execlp("ls", "ls", NULL) != -1, "execlp");
    } else {
        char cs[10000];
        read(fd[0], cs, sizeof cs);
        printf("STARTn%snENDn", cs);
    }
    return EXIT_SUCCESS;
}

Advertisement

Answer

You have the order of the dup2( existing_fd, new_fd ) parameters reversed.

You have another bug that breaks lots of “let’s try out pipe(2)” experiments. You aren’t closing the ends of the pipe that get duplicated over the fork. This normally causes a different sort of hang because the reader doesn’t ever see an EOF, as the reader process has an extra copy of the pipe’s writer end so closing just the writer process’s end isn’t enough to give the reader an EOF.

So, get in the habit:

if (pid == 0) {
    check(dup2(fd[1], 1) != -1, "dup2");
    close(fd[1]); // Here!
    close(fd[0]); // ...and here!
    check(execlp("ls", "ls", NULL) != -1, "execlp");
} else {
    char cs[10000];
    close(fd[1]); // and here!
    ...
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement