Question

I would like to use pipes to redirect stdin and stdout of a child process.

At the moment I have the following code:

void child(int pipeIn[], int pipeOut[]) {

    char buff[20];
    const char msg[]="Child Message\n";
    close(pipeIn[1]);
    close(pipeOut[0]);

    if (dup2(pipeIn[0], 0))
        perror("dup2 pipeIn");

    if (dup2(pipeOut[1], 1))
        perror("dup2 pipeOut");

    close(pipeIn[0]);
    close(pipeOut[1]);

    for (int i = 0; i < 10; ++i) {
        read(0, buff, 20);
        fprintf(stderr, "Child: %s\n",buff);
        printf("%s",msg);
    }
}

void parent(int pipeIn[], int pipeOut[]) {

    char buff[20];

    const char msg[]="Parent Message\n";
    close(pipeIn[0]);
    close(pipeOut[1]);

    for (int i = 0; i < 10; ++i) {
        write(pipeIn[1], msg, 16);
        read(pipeOut[0], buff, 50);
        printf("Parent: %s", buff);

    }

}

void test() {

    int pipeOut[2],pipeIn[2];

    if(pipe(pipeOut)) {
        perror("pipeOut");
        exit(1);
    }

    if(pipe(pipeIn)) {
        perror("pipeIn");
        exit(1);
    }

    int pid = fork();

    if (pid == -1) {
        perror("fork()");
        exit(1);
    } 
    else if (pid == 0) 
        child(pipeIn, pipeOut);
    else 
        parent(pipeIn,pipeOut);

}

This code, however, is not working because I keep getting

dup2 pipeOut: Undefined error: 0

And it ends up in deadlock.
I understand that the code halts because the parent keeps waiting for the answer of the child (that never arrives) and the same the child keeps waiting for an input that never arrives.

What I do not understand is why I keep getting that error. Am I doing something wrong?

I am working on MacOS Lion 10.7.2 and Xcode 4.2.1.


UPDATE: after Adam Rosenfield's answer I corrected my if statement. However the code still halts as I said (I'm only able to read the first thing that the child prints Child: Parent Message and nothing else).

Any idea why this is happening?

Was it helpful?

Solution

dup2(2) returns a non-negative integer on success, namely the new file descriptor. It returns -1 on error. In your case, it's returning 0 on the first call because you're duplicating the pipe onto file descriptor 0.

To fix it, change your checks from if(dup2(...)) to if(dup2(...) == -1).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top