C++執行shell命令-linux


在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來產生子進程,執行命令行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM