简体   繁体   中英

Terminate threads when SIGINT is called - C

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?

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 eg

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.

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