【问题标题】:how to redirect terminal command output via execve to std::string in c++如何通过execve将终端命令输出重定向到c ++中的std :: string
【发布时间】:2020-06-26 03:54:13
【问题描述】:

我想将终端中执行命令的输出重定向到 C++ 中的字符串。我不希望命令输出出现在终端中,因为我使用的是 ncurses 显示。 有什么办法可以做到吗?

我正在使用 Linux 终端。

我考虑过重定向到临时文件,然后读取文件的内容。但我更不想引入 tmp 文件。 澄清一下,我希望能够做到以下几点:

  1. 通过 execve 回显“hello world”
  2. 将终端的输出重定向到一个std::string,这样它实际上不会在这个阶段显示在终端中。
  3. 在 ncurses 中使用 printw 函数将命令输出打印到 ncurses 窗口

我目前正在寻找使用 termios.h 和可能的 dup2 功能的可能实现

我的代码如下所示:

std::string containerForOutput;


// some method which redicects execve into containerForOutput here

char cmd[100];
strcpy(cmd, "/usr/bin/");
strcat(cmd, argv[0]);

// execute the command using execve, but
// will not output to terminal after command is given
// and will instead store it in the string containerForOutput
int result = execve(cmd, argv, environ);
perror("Fallback Shell");

使用字符串流不起作用。

【问题讨论】:

  • 这个std::string应该存在于哪个进程中? 那个进程和生成数据的进程之间是什么关系?父母和孩子分别?你应该展示你到目前为止编写的代码。
  • this 发帖。

标签: c++ terminal termios


【解决方案1】:

一个不错的选择是使用 pstream 头文件而不是 execve,它会创建一个子进程。

感谢这篇文章:

https://stackoverflow.com/a/10702464/5133238

我不使用 exec 捕获输出并使用 ncurses printw 方法打印它:

  // run a process and create a streambuf that reads its stdout and stderr
  redi::ipstream proc("echo hello", redi::pstreams::pstdout | redi::pstreams::pstderr);
  std::string line;
  // read child's stdout
  while (std::getline(proc.out(), line)) {
   // the output is captured line by line here
   // so that i can do what i want with it
    printw(line.c_str());
    printw("\n");
  }

  // if reading stdout stopped at EOF then reset the state:
  if (proc.eof() && proc.fail()) {
    proc.clear();
  }
  // read child's stderr
  while (std::getline(proc.err(), line)) {
   // error message is captured line by line here
   // so that i can do what i want with it.
    printw(line.c_str());
    printw("\n");
  }

pstreams 在这里: http://pstreams.sourceforge.net/

【讨论】:

    猜你喜欢
    • 2014-10-11
    • 2012-11-15
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 2014-12-14
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多