Consider we have some_function
and it prints result to stdout
instead returning it.Changing it's defination is out of our scope and there's no alternative to it. We're left with option of reading it from stdout
. So the question.
How to read stdout of C++ program in itself.
It is possible to get pid
I searched if we can get fd
of the same programm but I'm not able to find anything.
#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;
}
How to attach pipe to same process i.e instead of creating child process.
Some might think of creating child process and call some_function
in it, to be able to read its stdout
in parent process, but No, some_function
depends on process which calls it and hence we want to call it the very process instead of creating child process.