我正在尝试编写一个 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/