Signal handler not working on process opened via pipe

你离开我真会死。 提交于 2020-01-16 08:16:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!