C++執行shell命令

在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 java");

    return 0;
}
  • system函數調用fork來產生子進程,執行命令行
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章