简体   繁体   中英

Linux - signal: error: invalid use of non-static member function

I originally wrote some tests to test the functionality of signals for my program. The tests proved promising, however moving the small code changes to my class in my source code has given me a few problems.

I have added two functions: setAlarm() , and a callback alarm_handler . setAlarm() does as it says, which is set the alarm. Once time expires, alarm handler is called which runs an execute function.

a.cpp

int Database::alarm_handler(int signum)
{
    dbExecSql();
}

void Database::setAlarm()
{
    signal(SIGALRM, alarm_handler);
    ualarm(500000,0);
}

bh

class Database
{
public:
    int alarm_handler(int signum);
    void setAlarm();
    dbExecSql();
};

error

error: invalid use of non-static member function
     signal(SIGALRM, alarm_handler);

Any help would be appreciated.

EDIT

I have modified alarm_handler to be removed from my class, however am now am receiving:

error: invalid conversion from ‘int (*)(int)’ to ‘__sighandler_t {aka void (*)(int)}’ [-fpermissive]
     signal(SIGALRM, alarm_handler);
                                  ^

The signal handler function ( alarm_handler ) can't be member function and should be a standalone function with C linkage.

Remove it from your class:

void alarm_handler(int signum)
{
    dbExecSql();
}

Beware that only async-signal-safe functions can be called from signal handlers safely. So you need to ensure dbExecSql() respects that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM