如何在 C++ 中使用 POSIX 执行命令并获取命令的输出?


你可以使用 popen 和 pclose 函数在进程中进行管道通信。popen() 函数通过创建管道、fork 和调用 shell 来打开一个进程。我们可以使用一个缓冲区读取 stdout 的内容,并将其一直附加到一个结果字符串中,并在进程退出时返回这个字符串。

示例

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

using namespace std;

string exec(string command) {
   char buffer[128];
   string result = "";

   // Open pipe to file
   FILE* pipe = popen(command.c_str(), "r");
   if (!pipe) {
      return "popen failed!";
   }

   // read till end of process:
   while (!feof(pipe)) {

      // use buffer to read and add to result
      if (fgets(buffer, 128, pipe) != NULL)
         result += buffer;
   }

   pclose(pipe);
   return result;
}

int main() {
   string ls = exec("ls");
   cout << ls;
}

输出

这将给出输出 -

a.out
hello.cpp
hello.py
hello.o
hydeout
my_file.txt
watch.py

更新于: 12-Feb-2020

12K+ 浏览量

开启你的 职业生涯

完成课程以获得认证

开始学习
广告
© . All rights reserved.