Catching signals: Use a member function as signal handler

前端 未结 2 546
-上瘾入骨i
-上瘾入骨i 2021-02-15 16:09

I have an object which does some work in an endless loop. The main() instantiates the object and calls the run() method. Since I don\'t want to use thr

相关标签:
2条回答
  • 2021-02-15 16:29
    • What do I need to change to make this work? I think f is like void f(int), like the functions the signal handler gets in some examples.

    The compiler complains about the type, therefore you need to pass a function pointer, not an object of type boost::function<void(int)>. Creating a global variable of this type, and adding a function which calls this object would work :

    boost::function<void(int)> myCb;
    void CallCb( int value )
    {
      myCb(value);
    }
    
    int main(int argc, char** argv)
    {
        Foo foo;
        struct sigaction sigIntHandler;
    
        myCb = std::bind1st(
          std::mem_fun(&Foo::catch_signal), &foo);
        f(5);  // this call works
    
        sigIntHandler.sa_handler = CallCb;
        sigemptyset(&sigIntHandler.sa_mask);
        sigIntHandler.sa_flags = 0;
        sigaction(SIGTERM, &sigIntHandler, NULL);
        s.run();
    
    }
    
    • Do you have any advice how to solve this kind of thing better?

    Not really. The idea is ok. I would just just c++11 lambda instead

    0 讨论(0)
  • 2021-02-15 16:48

    There is very little that you can do portably in a signal handler. Basically, you can store a value in an object whose type is sig_atomic_t. Inserting into cout, for example, doesn't have to work. If you have C++11 you can do a bit more, using atomic types or explicit fences, but any other calls into the standard library aren't required to do anything sensible.

    So, with all that said, what you can do is write a function (either a free function or a static member function (but there is a subtle issue here with C++ linkage: formally a static member function won't work, but in practice it always does)) that calls the member function, which in turn sets running to false (assuming you've changed the type of running to sig_atomic_t).

    0 讨论(0)
提交回复
热议问题