2010-07-27 67 views
3

我正在使用popen打开一个写入管道并将命令发送到应用程序。问题是,只有在关闭管道时才会将命令发送给应用程序。使用popen在管道中写入时只能在管道关闭时发送数据

FILE * fp = open(target_app, "w"); 
fwrite(command, 1, command.size(), fp); 
getchar(); //wait for a key, because I don't want to terminate the application 
pclose(fp); // at this point, the command is sent 

什么可能是错的?

回答

2

我只是弄清楚,我要冲洗管,而无需关闭它发送命令。我的修复程序是:

FILE * fp = open(target_app, "w"); 
fwrite(command, 1, command.size(), fp); 
fflush(fp); 
getchar(); //wait for a key, because I don't want to terminate the application 
pclose(fp); // at this point, the command is sent 
0

管道将不会发送数据,直到达到它的结尾。 你必须告诉你,这是结束,否则它会继续等待。

这样做的一种方法就是像你这样做:关闭管道。 另一个是使用fflush(在我看来最好)。 你也可以写一个\ n我猜,我很久没有写C++了。

+0

我已经试过\ n,但它不会工作。我能做到的唯一方法就是使用fflush。 – carlfilips 2010-07-27 23:47:43

+0

是的,因为这是做这件事的好方法:) – Shahor 2010-07-28 07:59:10

0

从手册页:

Note that output popen() streams are fully buffered by default. 

这意味着一个标准的实施方式中,512和8192之间的字节将必须被写入之前数据被自动刷新到底层的文件描述符。

要么调用fflush(),或者更好的,叫setvbuf(fp, nullptr, _IONBF, 0);