为什么在读取和写入管道时需要关闭fds?

时间:2010-04-17 14:31:06

标签: c

但是,如果我的一个进程需要连续写入管道而另一个管道需要读取呢?

此示例似乎仅适用于一次写入和一次读取。我需要多次读写

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

2 个答案:

答案 0 :(得分:1)

在子块中,您不需要关闭fds 1,2和3. dup2()将在必要时关闭oldfd。

在父块中,你不应该在读取和写入之前关闭管道fds!

对于多个管道,请使用非阻塞IO或select()

答案 1 :(得分: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);

在外部do / while循环的第一次迭代后关闭input[1],但每次迭代都需要该描述符。

此外,如果内部while循环,您将继续阅读,直到您获得EOF。但由于程序仍处于打开状态,因此在程序结束之前不会获得EOF。因此,您需要找到一些其他方式来了解该程序已经为您提供了所有输入。

相关问题