但是,如果我的一个进程需要连续写入管道而另一个管道需要读取怎么办?
这个例子似乎只适用于一次写入和一次读取。我需要多读写
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/