使用 C++ 读取进程本身的标准输出

mog*_*hya 2 c++ unix pid stdout process

考虑到我们有some_function ,它打印结果stdout而不是返回它。改变它的定义超出了我们的范围,没有其他选择。我们可以选择从stdout. 所以问题。

如何读取 C++ 程序本身的标准输出。

pid如果我们可以获得fd相同的程序,则可以搜索我,但我找不到任何东西。

#include <unistd.h>
#include <sys/types.h>
#include <iostream>
void some_function(){
    std::cout<<"Hello World";
}

int main(){


    int pid = ::getpid();
    string s = //What to write here.

    cout<<"Printing";

    some_function(); //This function prints "Hello World" to screen

    cout<<s; //"PrintingHello World"
    return  0;
}
Run Code Online (Sandbox Code Playgroud)

如何将管道附加到同一个进程,而不是创建子进程。

有些人可能会想到创建子进程并调用some_function它,以便能够stdout在父进程中读取它,但是不,some_function取决于调用它的进程,因此我们希望将其称为进程而不是创建子进程。

And*_*nle 5

这并不难做到,但在 IMO,这是一个相当大的黑客,它不适用于多线程程序:

// make a temp file to store the function's stdout
int newStdOut = mkstemp( "/tmp/stdout.XXXXXXX" );

// save the original stdout
int tmpStdOut = dup( STDOUT_FILENO );

// clear stdout
fflush( stdout );

// now point the stdout file descriptor to the file
dup2( newStdOut, STDOUT_FILENO );

// call the function we want to collect the stdout from
some_function();

// make sure stdout is empty
fflush( stdout );

// restore original stdout
dup2( tmpStdOut, STDOUT_FILENO );

// the tmp file now contains whatever some_function() wrote to stdout
Run Code Online (Sandbox Code Playgroud)

错误检查、正确的标题、将 Cstdout与 C++同步cout以及读取和清理临时文件都作为练习...;-)

请注意,您不能安全地使用管道 - 该函数可以写入足以填满管道的内容,并且您无法从管道中读取数据,因为您已经调用了该函数。