相关疑难解决方法(0)

将Spawned Process的输出捕获到字符串

背景:


我的工作需要能够捕捉程序stdout,stderr并返回程序的值.理想情况下,我想在我存储在我的对象中的字符串中捕获这些字符串,该字符串包含进程的详细信息.我目前有一些代码,通过使用一些(在我看来)古老的C文件句柄魔术将输出保存到文件中.任何时候我想输出结果,我打开该文件,然后打印内容.

有时(当我生成的进程继续运行时)我的可执行文件的下一次执行将会中断,因为它无法打开文件进行写入.

问题陈述:


我正在寻找一种方法来将stdout窗口中创建的进程的输出保存为一个字符串,并stderr以更安全,更现代的方式保存到另一个字符串.这样我就可以在每次输出每个创建过程的结果时打印这些内容.

我丑陋的代码:


主要块 -

    int stdoutold = _dup(_fileno(stdout)); //make a copy of stdout
    int stderrold = _dup(_fileno(stdout)); //make a copy of stderr
    FILE *f; 

    if(!fopen_s(&f, "name_of_my_file", "w")){ //make sure I can write to the file
        _dup2(_fileno(f), _fileno(stdout)); //make stdout point to f
        _dup2(_fileno(f), _fileno(stderr)); //make stderr point to f

        fork("command_I_want_to_run", &pi); //run my fake fork (see below)
    }
    else{
        ...//error handling
    }
    _close(_fileno(stdout)); //close tainted stdout
    _close(_fileno(stderr)); //close …
Run Code Online (Sandbox Code Playgroud)

c++ parallel-processing logging

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

c++ ×1

logging ×1

parallel-processing ×1