C 語言popen函數,實現shell和讀取內容

來源:互聯網
上載者:User

標籤:實現   一個   pen   popen   include   建立   緩衝   color   style   

1. popen()函數

標頭檔:#include <stdio.h>

函數原型:FILE * popen(const char * command, const char * type);

關閉檔案流:int pclose(FILE * stream);

  函數popen 先執行fork,然後調用exec以執行cmd,並且返回一個標準I/O檔案指標。

  cmd是一個包含shell命令的字串指標(以NULL結束字元結尾);
  如果type是"r",則檔案指標串連到cmd的標準輸出;
  如果type是"w",則檔案指標串連到cmd的標準輸入。

2. 描述

  popen() 函數用建立管道的方式啟動一個進程, 並調用 shell. 因為管道是被定義成單向的, 所以type參數只能定義成唯讀或者唯寫, 不能是兩者同時, 結果流也相應的是唯讀或者唯寫.

  command 參數是一個字串指標, 指向的是 一個以 null 結束符結尾的字串, 這個字串包含一個 shell 命令. 這個命令被送到 /bin/sh 以 -c 參數執行, 即由 shell 來執行. type 參數也是一個 指向以 null 結束符結尾的字串的指標, 這個字串必須是 ‘r‘ 或者 ‘w’ 來指明是讀還是寫.

   popen() 函數的傳回值是一個普通的標準I/O流, 它只能用 pclose() 函數來關閉, 而不是 fclose() 函數.

  注意, popen 函數的輸出資料流預設是被全緩衝的;pclose 函數等待相關的進程結束並返回一個 command 命令的退出狀態, 就像 wait4 函數 一樣

3. 樣本

 1 #include <stdio.h> 2  3 int main(void) 4 { 5     FILE * fp; 6     if ((fp = popen("ls -l", "r)) == NULL) 7     { 8         perror("open failed!"); 9         return -1;10     }11     char but[256];12     while (fgets(but, 255, fp) != NULL)13         printf("%s", buf);14     if (pclose(fp) == -1)15     {16         perror("close failed!");17         return -2;18     }19     return 0;20 }

 

C 語言popen函數,實現shell和讀取內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.