Terminate threads when SIGINT is called - C

谁说胖子不能爱 提交于 2021-02-10 14:51:05

问题


I'm building a generic program written in C-UNIX (using Linux so I don't care about BSD or WIN functions), that creates two threads to handle the communication with a server.

void init_threads(int socket_desc) {

    pthread_t chat_threads[2];

    ret = pthread_create(&chat_threads[0], NULL, receiveMessage, (void*)(long)socket_desc);
    PTHREAD_ERROR_HELPER(ret, "Errore creazione thread ricezione messaggi");

    ret = pthread_create(&chat_threads[1], NULL, sendMessage, (void*)(long)socket_desc);
    PTHREAD_ERROR_HELPER(ret, "Errore creazione thread invio messaggi");

}

Since this program will be launched from shell I want to implement the CTRL-C possibility and so did I with this line of code:

signal(SIGINT,kill_handler);
// and its related function
void kill_handler() {
        // retrive threads_id
        // call pthread_exit on the two threads
        printf("Exit from program cause ctrl-c, bye bye\n");
        exit(EXIT_SUCCESS);
      }

My question is how can I found out the thread ids inside the event handler function and is it correct to call pthread_exit or should I use something else?


回答1:


Don't call pthread_exit() from a signal handler! It is not required to be async-signal-safe, see signal-safety.

In general, you should do as little as possible in a signal handler. The common idiom is to just set a flag that is periodically checked in your main loop like e.g.

volatile sig_atomic_t exitRequested = 0;

void signal_handler(int signum)
{
    exitRequested = 1;
}

int main(void)
{
    // init and setup signals

    while (!exitRequested)
    {
        // do work
    }

    // cleanup
}

Also, use sigaction() for installing signal handlers. See signal() for reasons not to use it.



来源:https://stackoverflow.com/questions/44629212/terminate-threads-when-sigint-is-called-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!