简体   繁体   English

从C / C ++中的管道正确获取输出

[英]Properly getting output from a pipe in C / C++

I am writing C / C++ code to run a shell command and capture the output: 我正在编写C / C ++代码来运行shell命令并捕获输出:

static const int BUFFER_SIZE=512;

// (...)

FILE* pipe;
char buffer[BUFFER_SIZE];

// (...)

if (!(pipe = popen(cmd.c_str(), "r"))) {
  out("\nProblem executing command: " + cmd + "\n");
  return 1;
}

while (!feof(pipe)) {
  int read = fread(buffer, sizeof(char), sizeof buffer, pipe);
  int pos = -1;
  int i;

  for (i = 0; i < strlen(buffer); i++) {
    if (buffer[i] == '\n') {
      pos = i;
    }
  }

  // ... get a substring from buffer var from 0 to pos,
  // and set a "reminder" var with pos+1 to end of string
}

It's working with a glitch: I see that the buffer contain some non-ascii chars at the end that are messing up every other operation I do with the string afterwards (the substring I mentioned on the comment). 它正在发生故障:我看到缓冲区的末尾包含一些非ASCII字符,这些字符后来弄乱了我对字符串所做的每一次其他操作(我在评论中提到的子字符串)。

Here's an example of what I am seeing: 这是我所看到的示例:

错误示例

Since I am a C / C++ beginner, I'd like to ask advice on how can I can capture the process output and stream it somewhere else, splitting it when necessary. 由于我是C / C ++的初学者,所以我想就如何捕获过程输出并将其流传输到其他地方提出建议,在必要时进行拆分。 The code can be in C or C++. 代码可以是C或C ++。

fread does not NUL terminate the buffer, so strlen is not appropriate. fread不会NUL终止缓冲区,因此strlen是不合适的。

Use the result read to limit your loop. 使用read的结果来限制循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM