linux popen用法詳解

來源:互聯網
上載者:User

http://linux.chinaitlab.com/c/806015.html

函數原型:

  #include “stdio.h”

  FILE *popen( const char* command, const char* mode )

  參數說明:

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

  mode: 只能是讀或者寫中的一種,得到的傳回值(標準 I/O 流)也具有和 type 相應的唯讀或唯寫類型。如果 type 是 “r” 則檔案指標串連到 command 的標準輸出;如果 type 是 “w” 則檔案指標串連到command 的標準輸入。

  傳回值:

  如果調用成功,則返回一個讀或者開啟檔案的指標,如果失敗,返回NULL,具體錯誤要根據errno判斷

  int pclose (FILE* stream)

  參數說明:

  stream:popen返回的檔案指標

  傳回值:

  如果調用失敗,返回 -1

  作用:

  popen() 函數用於建立一個管道:其內部實現為調用 fork 產生一個子進程,執行一個 shell 以運行命令來開啟一個進程這個進程必須由 pclose() 函數關閉。

例子:

  管道讀:先建立一個檔案test,然後再test檔案內寫入“Readpipe successfully !”

  #include “stdio.h”

  #include “stdlib.h”

  int main()

  {

  FILE *fp;

  char buf[200] = {0};

  if((fp = popen(“cat test”, “r”)) == NULL) {

  perror(“Fail to popen\n”);

  exit(1);

  }

  while(fgets(buf, 200, fp) != NULL) {

  printf(“%s”, buf);

  }

  pclose(fp);

  return 0;

  }

  列印輸出: Read pipe successfully !

  管道讀:

  #include “stdio.h”

  #include “stdlib.h”

  int main()

  {

  FILE *fp;

  char buf[200] = {0};

  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 !

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.