c++ - 子进程通信。 C++

标签 c++ subprocess popen

我正在尝试编写一个 C++ 程序,它将启动新进程(一些脚本、程序、命令),如守护进程,并从中获取一些信息(stdout)。我正在尝试使用 popen()。但是子进程在主程序完成时完成。我不知道,C++ 是否有像 Python(子处理)这样易于使用的东西。这是我的代码:

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

using namespace std;

int main(int argc, char *argv[]) {
  FILE *in;
  char buff[512];
  in = popen(argv[1], "r");
  fgets(buff, sizeof(buff), in);
  cout << buff;
}

P.S: & 在执行命令的末尾没有帮助。

最佳答案

fgets 不会等待子进程完成,popen 也不会。

你需要一直读到 in 的结尾:

while (fgets(buff, sizeof(buff), in))
{
    cout << buff;
}

关于c++ - 子进程通信。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42229666/

相关文章:

c++ - 是否 sizeof(T) == sizeof(const T) 和 alignof(T) == alignof(const T)

c++ - 如何修复这个: Argument of type “const char*” is incompatible with the parameter of type "char** [duplicate]

c++ - 在 C++ 中使用 LibCurl 和自签名证书

python - 使用管道运行外部程序并在 python 中传递参数

c++ - 防止 popen 显示命令的输出

c++ - 更改 QTabWidget 的小部件的内容,只知道选项卡索引

python - subprocess.Popen() 错误(没有这样的文件或目录)调用带有参数作为字符串的命令

python - 为什么十六进制数字在 python 子进程中没有正确传递

Python子进程Exec格式错误

python - subprocess.Popen - 再次重定向标准输入