Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_cleanup_push handler not working for SIGINT (Ctrl C)

Tags:

c

linux

pthreads

I have a code similar to :

myThread()
{
    pthread_cleanup_push(CleanupHandler , NULL)
    while (true)
    {
      /* some code here */
    }
    pthread_cleanup_pop(NULL)

 }

 static void CleanupHandler(void *arg)
 {
   printf("Cleaned\n");
 }

But if I terminate my application using ^C (SIGINT), the cleanup handler is not working. Is that expected ? What is the workaround to make the CleanupHandler work at ^C ?

like image 674
Lunar Mushrooms Avatar asked Aug 26 '26 21:08

Lunar Mushrooms


1 Answers

Yes, this is expected, as per man page, pthread_cleanup_push() executes in following 3 circumstances:

      1) When a thread is canceled
      2) thread terminates using pthread_exit()
      3) when pthread_cleanup_pop()

To workaround your problem you can register a signal handler for SIGINT, from that handler use pthread_exit() or pthread_cancel() to execute your handler. Hope this helps!

like image 105
rakib_ Avatar answered Aug 28 '26 13:08

rakib_