2010-07-27 28 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);