问题
Note: this is a general question (not limited to wolfram
command, and you don't have to know about wolfram
).
I consider wrapping wolfram
(CUI calculator like python interpreter). Without any wrapper, SIGINT
causes the program to suspend the calculation.
$ /usr/bin/wolfram -noinit
In[1] := While[True, 1] #start infinite loop
#execute `kill -SIGINT` from another shell to send SIGINT
Interrupt> #calculation now interrupted (you can cancel or resume it)
However, with a wrapper, SIGINT
causes wolfram
to exit right now.
$ ./wrapper.out
In[1] := While[True, 1] #start infinite loop
#execute `kill -SIGINT` (the target is not the wrapper but the `wolfram` itself)
#`wolfram` exits right away
Caught SIGPIPE. #the wrapper recieves SIGPIPE
The full code of the wrapper is here. (The actual code is written better without exit(0)
and with a smart pointer, but the simplified code below still causes the problem.)
using namespace std;
#include <iostream>
#include <csignal>
void signal_handler(int signal) {
if (signal == SIGINT) {
cout << "Caught SIGINT.\n";
} else {
cout << "Caught SIGPIPE.\n";
}
exit(0); //not good since destructors aren't called
}
int main(int argc, char **argv) {
//set a signal handler
signal(SIGINT, signal_handler);
signal(SIGPIPE, signal_handler);
FILE *pipe = popen("/usr/bin/wolfram -noinit", "w");
while (true) {
string buf;
getline(cin, buf);
fprintf(pipe, "%s\n", buf.c_str());
fflush(pipe);
}
pclose(pipe);
}
Why, with a wrapper, is the signal handler of piped process ignored? And how can I keep the functionality of the original signal handler? man 3 popen
didn't give me any hint.
来源:https://stackoverflow.com/questions/57015738/signal-handler-not-working-on-process-opened-via-pipe