tags:

views:

61

answers:

2

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);
    }
}
+1  A: 

In child block, you don't need to close fds 1,2,and 3. dup2() will close oldfd if necessary.

In parent block, you shouldn't be closing the pipe fds before reading and writing to them!

For multiple pipes, use non-blocking IO or select()

Sean A.O. Harney
How can I do this?Any suggestions?Right now I am not able to resolve this problem ...
+1  A: 

Your code looks a bit off. Specifically here:

    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);

You close input[1] after the first iteration of the outside do/while loop but need that descriptor for each iteration.

Also, if the inner while loop, you will keep reading until you get EOF. But since the program is still open, you won't get EOF until the program ends. So you need to find some other way to know that the program has given you back all your input.

R Samuel Klatchko
Yes, this has been my problem. Any suggestions?