Why does using process substitution here cause a hang?

Viewed 76

I have a program which needs to launch other programs, possibly substituting their stdio with files and pipes. While it appears to "work" in that the sub-process does get it's I/O from the source pipe, unfortunately, it also causes a hang. The sub-process is seemingly never getting an EOF.

Here is a minimal reproduction of the code, why does this hang after printing "Hello World\n"?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

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

    switch (pid_t pid = fork()) {
    case 0: {
        // in child

        // replace the child's stdin with whatever filename is given as argv[1]
        freopen(argv[1], "r+b", stdin);

        // construct an argv array for to exec, no need for anything except 
        // argv[0] since we want it to use stdin
        char path[]  = "/bin/cat";
        char *args[] = {path, NULL};

        // run it!
        execv(args[0], args);
        abort(); // we should never get here!
    }
    case -1:
        // error
        return -1;
    default: {
        // in parent, just wait for the sub-process to terminate
        int status;
        const auto r = waitpid(pid, &status, __WALL);

        if (r == -1) {
            perror("waitpid");
            return -1;
        }
        break;
    }
    }
}
# runs printf creating a pipe, which is then passed as the argv of my test program
./test >(printf "Hello\n")
1 Answers
./test <(printf "Hello\n")

Switch to >(...) to <(...) to read from printf rather than write to it.

freopen(argv[1], "rb", stdin);

Don't use r+. You're only reading from the file, so make it r.

Related