开发者

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

开发者 https://www.devze.com 2022-12-27 10:52 出处:网络
However, what if one of my processes needs to continuously write to the pipe while the other pipe needs to read?

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

    pi开发者_运维百科pe(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);
    }
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号