In our program we are forced to call another program via popen()
. The structure is basically
// external program
int main() {
// does some stuff
std::cout << xml << std::endl;
}
// our programm
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe)
throw std::runtime_error("popen() failed!");
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)
result += buffer.data();
return result;
}
int main() {
const std::string xmlResult = exec("externalProgramm(.exe) --param1 --param2"); // Windows and Linux
// do something with the result
}
From time to time the external program freezes, thus freezing our program inside fgets()
. I tried to get around this problem but I cant find anything. The only solution seems to be to create a thread, wait some timeout time and if it doesnt finish in that time, .detach()
it. While this solution might work for short-lived programs, ours needs to run for weeks and makes a few million calls to the external program.
Is there any way to destroy a thread or read from a popen()
file without blocking everything? I know the real solution would be to "just dont call an external program that way" but we really have no other choice.
The solution needs to work on Windows and Linux. Giving my "duplicates" that only solve this on Linux does not answer my question.