c - 为什么读写管道时需要关闭fds?

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

最佳答案

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

在父 block 中,你不应该在读写之前关闭管道 fds!

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

关于c - 为什么读写管道时需要关闭fds?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2658674/

相关文章:

c++ - 内核函数参数为 const

c++ - 如何确保 C/C++ 代码中不缺少 doxygen 样式的文档注释?

c - 打印语句的输出是什么?

c中的编译器错误链表

c++ - 如何在 x64 Visual C++ 中执行裸函数和内联汇编程序

objective-c - 如何从 Objective C 方法返回二维 C 样式数组?

c - 编译器第一次到达 C 程序中的#include 语句时执行什么功能

c - 在c中找到合数的最大质因数

c - 如何从 EFI 棒更改 msr 0x199?

c - 不会接收从服务器到客户端的完整数据 (unix - C)