Why do I need to close fds when reading and writing to the pipe?

Posted by valentimsousa on Stack Overflow See other posts from Stack Overflow or by valentimsousa
Published on 2010-04-17T14:31:06Z Indexed on 2010/04/17 14:33 UTC
Read the original article Hit count: 199

Filed under:

However, what if one of my processes needs to continuously write to the pipe while the other pipe needs to read?

This example seems to work only for one write and one read. I need multi read and write

void executarComandoURJTAG(int newSock) { int input[2], output[2], estado, d; pid_t pid; char buffer[256]; char linha[1024];

pipe(input);
pipe(output);
pid = fork();

if (pid == 0) {// child

    close(0);
    close(1);
    close(2);
    dup2(input[0], 0);
    dup2(output[1], 1);
    dup2(output[1], 2);

    close(input[1]);
    close(output[0]);
    execlp("jtag", "jtag", NULL);
}

else { // parent
    close(input[0]);
    close(output[1]);
    do {
        read(newSock, linha, 1024);
        /* Escreve o buffer no pipe */
        write(input[1], linha, strlen(linha));
        close(input[1]);
        while ((d = read(output[0], buffer, 255))) {
            //buffer[d] = '\0';
            write(newSock, buffer, strlen(buffer));
            puts(buffer);
        }
        write(newSock, "END", 4);

    } while (strcmp(linha, "quit") != 0);
}

}

© Stack Overflow or respective owner

Related posts about c