Linux下使用popen 執行shell命令

2022-04-16 11:07:12 字數 1166 閱讀 3207

**於:

簡單說一下popen()函式

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

int pclose(file *stream);

popen()函式通過建立乙個管道,呼叫fork()產生乙個子程序,執行乙個shell以執行命令來開啟乙個程序。這個管道必須由pclose()函式關閉,而不是fclose()函式。pclose()函式關閉標準i/o流,等待命令執行結束,然後返回shell的終止狀態。如果shell不能被執行,則pclose()返回的終止狀態與shell已執行exit一樣。

type引數只能是讀或者寫中的一種,得到的返回值(標準i/o流)也具有和type相應的唯讀或只寫型別。如果type是"r"則檔案指標連線到command的標準輸出;如果type是"w"則檔案指標連線到command的標準輸入。

command引數是乙個指向以null結束的shell命令字串的指標。這行命令將被傳到bin/sh並使用-c標誌,shell將執行這個命令。

popen()的返回值是個標準i/o流,必須由pclose來終止。前面提到這個流是單向的(只能用於讀或寫)。向這個流寫內容相當於寫入該命令的標準輸入,命令的標準輸出和呼叫popen()的程序相同;與之相反的,從流中讀資料相當於讀取命令的標準輸出,命令的標準輸入和呼叫popen()的程序相同。

如果呼叫fork()或pipe()失敗,或者不能分配記憶體將返回null,否則返回標準i/o流。popen()沒有為記憶體分配失敗設定errno值。如果呼叫fork()或pipe()時出現錯誤,errno被設為相應的錯誤型別。如果type引數不合法,errno將返回einval。

//execute shell command

//執行乙個shell命令,輸出結果逐行儲存在resvec中,並返回行數

int32_t myexec(const char *cmd, vector&resvec)

char tmp[1024]; //設定乙個合適的長度,以儲存每一行輸出

while (fgets(tmp, sizeof(tmp), pp) != null)

resvec.push_back(tmp);

}pclose(pp); //關閉管道

return resvec.size();

}

Linux下使用popen 執行shell命令

簡單說一下popen 函式 include file popen const char command const char type int pclose file stream popen 函式通過建立乙個管道,呼叫fork 產生乙個子程序,執行乙個shell以執行命令來開啟乙個程序。這個管道必...

Linux下使用popen 執行shell命令

簡單說一下popen 函式 include file popen const char command const char type int pclose file stream popen 函式通過建立乙個管道,呼叫fork 產生乙個子程序,執行乙個shell以執行命令來開啟乙個程序。這個管道必...

Linux下使用popen 執行shell命令

簡單說一下popen 函式 include file popen const char command const char type int pclose file stream popen 函式通過建立乙個管道,呼叫fork 產生乙個子程序,執行乙個shell以執行命令來開啟乙個程序。這個管道必...