SpamBot
SpamBot

Reputation: 1458

Library overwrites signal handler, but I need to clean up on CTRL+C

I write a terminal application that uses a device controlled by a poorly designed library that overwrites SIGINT (CTRL+C). My goal is to use the device correctly using that library, but I want to be able to close my application nicely with some cleaning up. (Otherwise, I would not follow the protocol of other devices I connect to and could not re-connect when running the program again.)

Here is what I tried:

std::atomic< bool > globalQuit(false);

void signalHandler(int signal)
{
    globalQuit = true;
}

int
main(int argc, char** argv)
{
    std::signal(SIGINT, signalHandler);
    badLibraryCall();
    while (!globalQuit)
    {
        badLibraryCall();
    }
    doCleanUp();
    return 0;
}

However, when I hit CTRL+C, a different signalHandler that is registered in badLibraryCall is called and exits. No nice doCleanUp is done.

Upvotes: 4

Views: 140

Answers (1)

pilcrow
pilcrow

Reputation: 58681

Mostly you are out of luck unless you play really dirty tricks like using LD_PRELOAD to override signal or sigaction behavior when you can reasonably infer that you're inside in the bad library.

However, you might be able to run badLibraryCall in a separate process, a child of your main process. Then your trapping of SIGINT could reap it, killing as needed, and perform whatever cleanup you need to do.

Upvotes: 2

Related Questions