What 's the meaning of the number 1 in SIG_IGN macro definition?

前端 未结 2 1453
清歌不尽
清歌不尽 2021-01-24 17:00
#define SIG_IGN     (void (*)(int))1
#define SIG_HOLD    (void (*)(int))5
#define SIG_ERR     ((void (*)(int))-1)

I know what (void (*)(int))

2条回答
  •  攒了一身酷
    2021-01-24 17:16

    Add a useful reference material as to the accepted answer.

    From APUE:

    If we examine the system’s header , we will probably find declarations of the form

    #define SIG_ERR (void (*)()) -1
    #define SIG_DFL (void (*)())  0
    #define SIG_IGN (void (*)())  1
    

    These constants can be used in place of the ‘‘pointer to a function that takes an integer argument and returns nothing,’’ the second argument to signal, and the return value from signal. The three values used for these constants need not be −1, 0, and 1. They must be three values that can never be the address of any declarable function. Most UNIX systems use the values shown.

    Yes, it ensures you will get a error when you try to do stupid things like me (maybe other (useful/stupid) things, I don't know):

    #include 
    #include 
    
    void signal_handler(int signal)
    {
        printf("hahahah\n");
    }
    
    int main(void)
    {
        void (*f1)(int);
        f1 = signal(SIGINT, signal_handler);
        f1(3);  //Get signal SIGSEGV and failed
                //Here I am calling SIG_DFL(3).
        raise(SIGINT);
    }
    

    Here calling f1(3) equals calling SIG_DFL(3), every function has an address but SIG_DFL (0) is not a valid one, so I get SIGSEGV error.

    SIGSEGV This signal indicates that the process has made an invalid memory reference (which is usually a sign that the program has a bug, such as dereferencing an uninitialized pointer).

提交回复
热议问题