1. 程式人生 > >popen——獲取Shell命令的輸出

popen——獲取Shell命令的輸出

(system(cmd),僅執行命令,是否成功,成功返回0,其他返回負數。) 

以前在C程式中習慣用system來呼叫執行shell命令,但是這樣有個缺點,就是隻能得到執行的shell命令的返回值,如果想得到其輸出,只能通過一些間接的方法,比如修改shell命令讓它的輸出重定向到一檔案中,然後c程式再從該檔案獲取。這樣的缺點是需要磁碟操作,降低了程式的執行效率。


如果用popen即可解決這個問題。
#include 
FILE *popen(const char *cmdstring, const char *type) ;
函式popen 先執行fork,然後呼叫exec以執行cmdstring,並且返回一個標準I/O檔案指標。
如果type是"r",則檔案指標連線到cmdstring的標準輸出;
如果type是"w",則檔案指標連線到cmdstring的標準輸入。

下面的例子用wget或curl從網上抓取一個網頁,然後把該網頁輸出到終端:

#include 

int

 main()
{
    FILE *fp;
    if ((fp = popen("wget www.baidu.com -O -", "r")) == NULL) {//用“curl 
www.baidu.com”也是一樣的
        perror("popen failed");
        return -1;
    }
    char buf[256];
    while (fgets(buf, 255, fp) != NULL) {
     printf("%s", buf);
    }
    if (pclose(fp) == -1) {
        perror(
"pclose failed");
        return -2;
    }
    return 0;
}