问题描述
确定我已创建两个管的程序 - >叉 - >儿童的stdin和stdout重定向到每个管道的一端 - >的父被连接到管道的另一端,并尝试读取关联的流与孩子的输出,并将其打印到屏幕上(我也将它写孩子的输入最终)。
OK I have a program that creates two pipes -> forks -> the child's stdin and stdout are redirected to one end of each pipe -> the parent is connected to the other ends of the pipes and tries to read the stream associated with the child's output and print it to the screen (and I will also make it write to the input of the child eventually).
问题是,当父母试图FGETS孩子的输出流,它只是摊位,等待,直到孩子死亡给FGETS,然后打印输出。如果孩子不退出,它只是等待永远。到底是怎么回事?我想,也许与fgets将阻塞,直到有东西在流,但直到孩子放弃它的文件描述符不能阻止所有的方式。
The problem is, when the parent tries to fgets the child's output stream, it just stalls and waits until the child dies to fgets and then print the output. If the child doesn't exit, it just waits forever. What is going on? I thought that maybe fgets would block until SOMETHING was in the stream, but not block all the way until the child gives up its file descriptors.
下面是code:
Here is the code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
FILE* fpin;
FILE* fpout;
int input_fd[2];
int output_fd[2];
pid_t pid;
int status;
char input[100];
char output[100];
char *args[] = {"/somepath/someprogram", NULL};
fgets(input, 100, stdin); // the user inputs the program name to exec
pipe(input_fd);
pipe(output_fd);
pid = fork();
if (pid == 0) {
close(input_fd[1]);
close(output_fd[0]);
dup2(input_fd[0], 0);
dup2(output_fd[1], 1);
input[strlen(input)-1] = '\0';
execvp(input, args);
}
else {
close(input_fd[0]);
close(output_fd[1]);
fpin = fdopen(input_fd[1], "w");
fpout = fdopen(output_fd[0], "r");
while(!feof(fpout)) {
fgets(output, 100, fpout);
printf("output: %s\n", output);
}
}
return 0;
}
推荐答案
孩子应该大概的
它的输出,和/或终止线路正常。否则,I / O缓冲可以挂在数据相当长一段时间。
The child should probably fflush()
its output, and/or terminate lines properly. Otherwise the I/O buffering can hang on to the data for quite a while.
您可以尝试设置 O_NONBLOCK
标记(使用的
)交出控制之前,但会要求你你的父母code的相应变化。仿佛在评论中指出,这不会帮助你克服在C标准库级别上进行缓冲,如果孩子使用文件
为主的I / O。
You can try to set the O_NONBLOCK
flag (using fcntl()
) on the child's output file descriptor before handing over control, but that will require you to change your parent code's accordingly. As pointed out in comments though, this won't help you overcome the buffering done at the C standard library level if the child uses FILE
-based I/O.
这篇关于不能从流中读取,直到孩子退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!