函數原型:
#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() 函數關閉。
例子一
popen執行完後,讀取內容
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *fp = NULL;
char buf[10240] = {0};
fp = popen("ls -al","r");
if(fp == NULL){
return 0;
}
fread(buf, 10240, 1, fp);
printf("%s\n",buf);
pclose(fp);
return 0;
}
例子二
popen執行完後,仍然可以向管道繼續傳送命令,實現功能
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *fp = NULL;
char buf[10240] = {0};
fp = popen("mysql -u root -p123456 my_db","w");
if(fp == NULL){
return 0;
}
fprintf(fp,"delete from my_test_table;");
fprintf(fp,"\\q");
pclose(fp);
return 0;
}