C 为什么在读取和写入管道时需要关闭fds?
但是,如果我的一个进程需要连续写入管道,而另一个管道需要读取,该怎么办 这个例子似乎只适用于一次写入和一次读取。我需要多读多写C 为什么在读取和写入管道时需要关闭fds?,c,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 =
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);
}
}
在子块中,不需要关闭fds 1、2和3。如有必要,dup2()将关闭oldfd 在父块中,在读取和写入管道FD之前,不应关闭管道FD
对于多个管道,使用非阻塞IO或select()您的代码看起来有点不对劲。具体而言:
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。因此,您需要找到其他方法来知道程序已将所有输入返回给您。是的,这一直是我的问题。有什么建议吗?我怎么做?有什么建议吗?现在我无法解决这个问题。。。