在linux系統下,用C++程序執行shell命令有多種方式
管道方式
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
int main()
{
FILE *pp = popen("cd /xxxx && ls -l", "r"); // build pipe
if (!pp)
return 1;
// collect cmd execute result
char tmp[1024];
while (fgets(tmp, sizeof(tmp), pp) != NULL)
std::cout << tmp << std::endl; // can join each line as string
pclose(pp);
return 0;
}
popen會調用fork來產生子進程,由子進程來執行命令行
子進程建立管道連接到輸入輸出,返回文件指針,輸出執行結果
系統調用方式
#include <cstdlib>
int main()
{
system("ps -ef| grep myprocess");
return 0;
}
system函數調用fork來產生子進程,執行命令行