Search code examples
cwindowswinapisignals

What should winapi signal handler return?


In its documentation, the windows c runtime library function: void __cdecl *signal(int sig, int (*func)(int, int)); is defined to take a signal handler func which returns an int.

I couldn't find in the very documentation, an explanation of what this int should be.


Solution

  • This is the definition of signal in the linked documentation:

    void __cdecl *signal(int sig, int (*func)(int, int));
    

    But signal is defined as a standard library C function (aligned with the POSIX standard but that is besides the point in Windows), so if the MS documentation fails, the next best thing is the C standard.

    Looking at the C specification, signal is, quite confusingly, defined as:

    #include <signal.h>
    void (*signal(int sig, void (*func)(int)))(int);
    

    Looking at the VisualStudio C header file signal.h (removing some MS-ism macros for clarity), the definition is clearer with the help of a typedef for the function pointer type, but equivalent:

    typedef void (* _crt_signal_t)(int);
    _crt_signal_t __cdecl signal(int _Signal, _crt_signal_t _Function);
    

    Note that the _crt_signal_t typedef is internal and undocumented. It should not be used in portable code.

    So the documentation is wrong: there is only one int argument to the signal callback and it should return void.

    Curiously, the example in the linked documentation gets it right:

    void SignalHandler(int signal) { /* ... */ }
    
    int main()
    {
        typedef void (*SignalHandlerPointer)(int);
    
        SignalHandlerPointer previousHandler;
        previousHandler = signal(SIGABRT, SignalHandler);
        /* ... */
    }