1

I have written a short command line application which uses a library to do some network communications. The network communication library needs to be initialized before usage, and has a destroy function which needs to be called for the network stack to be torn down correctly when the application exits.

class NetworkTester
{
public:
    NetworkTester()
    {
        cout << "Creating NetworkStack" << endl;
        NetworkStack::create();
        reader = new NetworkReader();
    }

    ~NetworkTester()
    {
        cout << "Destroying NetworkStack" << endl;
        delete reader;
        NetworkStack::destroy();
    }

    void poll()
    {
        Duration waitTime = MillisecondsDuration(1 * 1000);

        while (reader->read(networkData, waitTime))
        {
            // do stuff
        }
    }

private:
    NetworkReader * reader;
    NetworkData networkData {};
};

int main(int argc, char ** argv)
{
    NetworkTester tester {};

    while(1)
    {
        // do stuff
    }

    return 1;
}

I'm having some trouble with this however, as when I use ctrl+c to send a SIGINT signal to the process and thereby kill it, the destructor of NetworkTester is not being called. This means that my dynamically allocated NetworkReader is not being freed, and more importantly NetworkStack::Destroy is not being called. This is causing the network stack to fail to initialise correctly the next time it is used.

I have tested my destructor by creating an object in a scope and seeing the output from the destructor, so I'm fairly sure that my destructor code is fine.

What I would like to understand is what is happening when SIGINT is received by the program and why aren't variables on the stack being correctly destroyed - does anyone have any thoughts on this?

  • `while(1) {}` is a infinite loop without sideeffects, hence stricly speaking your program has undefined behavior and any output is "ok" – 463035818_is_not_an_ai Dec 09 '21 at 12:24
  • you could fix that by making the loop finite and add a `sleep` in the body. I suppose the question is not actually about UB due to infinite loops – 463035818_is_not_an_ai Dec 09 '21 at 12:25
  • 2
    related https://stackoverflow.com/questions/482702/using-sigint – 463035818_is_not_an_ai Dec 09 '21 at 12:28
  • The default handling of `SIGINT` is for the receiving process to immediately terminate abnormally. One aspect of that is not doing stack unwinding, so destructors of objects of automatic storage duration are not called. If you want destructors to be called, you need to explicitly handle the signal and take action to ensure the destructors are called. More info at https://stackoverflow.com/questions/4250013/is-destructor-called-if-sigint-or-sigstp-issued – Peter Dec 09 '21 at 12:40

0 Answers0