I am trying to create a new process (which shouldn’t block the current program) in C++, and to have the C++ listen for a message. When the message arrives, I want to run some more code.
I have this method which executes the command and results the result immediately, but I have no idea how to make one that runs code when the process returns a message:
string exec(const char* cmd)
{
// popen for *nix
FILE* pipe = _popen(cmd, "r");
if (!pipe)
return "";
char buffer[128];
string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
// pclose for *nix
_pclose(pipe);
return result;
}
Note: it may take a 1-3 seconds until the process returns the message — and the process will continue execution after that so the above code is not sufficient as the executed program will never end.
You could put the code which executes the process in a separate thread, that way the primary thread can continue to execute while the secondary thread starts the process and waits for the message from the child process.