歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Linux下使用popen()執行shell命令

Linux下使用popen()執行shell命令

日期:2017/3/1 9:31:59   编辑:SHELL編程

簡單說一下popen()函數

函數定義
#include <stdio.h>

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<string> &resvec) {
resvec.clear();
FILE *pp = popen(cmd, "r"); //建立管道
if (!pp) {
return -1;
}
char tmp[1024]; //設置一個合適的長度,以存儲每一行輸出
while (fgets(tmp, sizeof(tmp), pp) != NULL) {
if (tmp[strlen(tmp) - 1] == '\n') {
tmp[strlen(tmp) - 1] = '\0'; //去除換行符
}
resvec.push_back(tmp);
}
pclose(pp); //關閉管道
return resvec.size();
}

上面的那個vector<string>感覺不是很常用,所以改成一下sting版本了:

int myexec(const char *cmd, string &resvec)
{
resvec.clear();
FILE *pp = popen(cmd, "r"); //建立管道
if (!pp)
{
return -1;
}
char tmp[1024]; //設置一個合適的長度,以存儲每一行輸出
while (fgets(tmp, sizeof(tmp), pp) != NULL)
{
if (tmp[strlen(tmp) - 1] == '\n')
{
tmp[strlen(tmp) - 1] = '\0'; //去除換行符
}
resvec.append(tmp);
}
pclose(pp); //關閉管道
return resvec.size();
}

使用時候:

string str_kernel;
myexec("uname -sr",str_kernel);
cout<<str_kernel<<endl;

Shell編程淺析 http://www.linuxidc.com/Linux/2014-08/105379.htm

Linux Shell參數替換 http://www.linuxidc.com/Linux/2013-06/85356.htm

Shell for參數 http://www.linuxidc.com/Linux/2013-07/87335.htm

Linux/Unix Shell 參數傳遞到SQL腳本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell腳本中參數傳遞方法介紹 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell腳本傳遞命令行參數 http://www.linuxidc.com/Linux/2012-01/52192.htm

Linux Shell 通配符、轉義字符、元字符、特殊字符 http://www.linuxidc.com/Linux/2014-10/108111.htm

Copyright © Linux教程網 All Rights Reserved