C – pthread_cleanup_push handler does not apply to SIGINT (Ctrl C)

pthread_cleanup_push handler does not apply to SIGINT (Ctrl C)… here is a solution to the problem.

pthread_cleanup_push handler does not apply to SIGINT (Ctrl C)

I have a similar code :

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 with ^C (SIGINT), the cleanup handler won’t work. Is this expected? What is the workaround to make CleanupHandler work in ^C?

Solution

Yes, this is expected, according to the man page, pthread_cleanup_push() is performed in the following 3 cases:

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

To solve your problem, you can register a signal handler for SIGINT from which your handler is executed using pthread_exit() or pthread_cancel(). Hope this helps!

Related Problems and Solutions