0
votes

I would like to create a simple class to signals handling (just for study) with std::bind. However, I could not compile this code:

#include <iostream>
#include <functional>
#include <csignal>
using namespace std;

class SignalHandler
{   
public:

    void handler(int value)
    {
        cout << value << endl;
    }

    SignalHandler()
    {
        auto callback = std::bind(&SignalHandler::handler, this, std::placeholders::_1);

        sighandler_t ret = std::signal(SIGTERM, callback);
        if (SIG_ERR == ret) {
            throw;
        }
    }

};

int main() {

    SignalHandler handler;

    raise(SIGTERM);

    return 0;
}

(GCC) Compiler exit: prog.cpp: In constructor 'SignalHandler::SignalHandler()': prog.cpp:21:51: error: cannot convert 'std::_Bind(SignalHandler*, std::_Placeholder<1>)>' to '__sighandler_t {aka void ()(int)}' for argument '2' to 'void ( signal(int, __sighandler_t))(int)' sighandler_t ret = std::signal(SIGTERM, callback);

1
std::signal is from C. C doesn't know functors but functions. So std::signal expects a function pointer. So non-global state for your handler isn't possible.Columbo

1 Answers

1
votes

You can use static methods to handle SIGTERM, et al. I've done that before. static was the key to get signatures to match.