popen的用法及與system呼叫的區別

2021-09-22 22:19:10 字數 1368 閱讀 6032

首先用man檢視下popen的介紹:

popen, pclose - pipe stream to or from a process

#include 

file *popen(const char *command, const char *type);

int pclose(file *stream);

popen總是和pclose一起出現被使用的。popen() 建立乙個管道,通過fork或者invoke乙個子程序,然後執行command。返回值在標準io流中,由於是在管道之中,因此資料流是單向的,command只能產生stdout或者讀取stdin,因此type只有兩個值:『w』或『r』。r表示command從管道中讀取資料流,而w表示command的stdout輸出到管道中。command無法同時讀取和輸出。popen返回該fifo資料流的指標。

舉例用法(

管道讀:先建立乙個檔案test,然後再test檔案內寫入「read pipe successfully !」

#include 「stdio.h」

#include 「stdlib.h」

int main()

file *fp;

char buf[200] = ;

if((fp = popen(「cat test」, 「r」)) == null) ;

if((fp = popen(「cat > test1″, 「w」)) == null) {

perror(「fail to popen\n」);

exit(1);

fwrite(「read pipe successfully !」, 1, sizeof(「read pipe successfully !」), fp);

pclose(fp);

return 0;

執行完畢後,當前目錄下多了乙個test1檔案,開啟,裡面內容為read pipe successfully !

對於管道讀例子已經很清楚,而管道寫可能用的地方比較少。而對於寫可能更常用的是system函式:

system("cat "read pipe successfully!" > test1")

可以看出,popen可以控制程式的輸入或者輸出,而system的功能明顯要弱一點,比如無法將ls的結果用到程式中。如果不需要使用到程式的i/o資料流,那麼system是最方便的。

而且system函式是c89和c99中標準定義的,可以跨平台使用。而popen是posix 標準函式,可能在某些平台無法使用(windows應該是可以的吧,沒做過測試)。

如果上述兩個函式還無法滿足你的互動需求,那麼可以考慮exec函式組了。

Linux中的popen函式和system函式

說在前面 在實際程式設計中儘量減少使用system函式。int system const char command 說明 system 通過呼叫 bin sh c命令執行命令中指定的命令,並在命令完成後返回。在執行該命令期間,sigchld將被阻塞,並且sigint和sigquit將被忽略。返回值 ...

system與popen函式的效率

我們在程式中希望執行shell命令的時候首先想到的system函式,這個函式很簡單,但有乙個嚴重的問題,就是他的執行方式,效率上可能不高。include include include include include using namespace std timeval start,end dou...

nohup 與 的區別及用法

nohup 如果你正在執行乙個程序,而且你覺得在退出帳戶時該程序還不會結束,那麼可以使用n o h u p命令。該命令可以在你退出帳戶之後繼續執行相應的程序。n o h u p就是不掛起的意思 no hang up 在linux unix下,只有守護程序在脫離終端後能繼續執行,而普通程序在關閉終端時...