Main Content

Use of signal to kill thread

Uncaught signal kills entire process instead of specific thread

Description

This defect occurs when you use an uncaught signal to kill a thread. For instance, you use the POSIX® function pthread_kill and send the signal SIGTERM to kill a thread.

Risk

Sending a signal kills the entire process instead of just the thread that you intend to kill.

For instance, the pthread_kill specifications state that if the disposition of a signal is to terminate, this action affects the entire process.

Fix

Use other mechanisms that are intended to kill specific threads.

For instance, use the POSIX function pthread_cancel to terminate a specific thread.

Examples

expand all

#include <signal.h>
#include <pthread.h>

void* func(void *foo) {
  /* Execution of thread */
}
 
int main(void) {
  int result;
  pthread_t thread;
 
  if ((result = pthread_create(&thread, NULL, func, 0)) != 0) {
  }
  if ((result = pthread_kill(thread, SIGTERM)) != 0) {
  }
 
  /* This point is not reached because the process terminates in pthread_kill() */
 
  return 0;
}

In this example, the pthread_kill function sends the signal SIGTERM to kill a thread. The signal kills the entire process instead of the thread previously created with pthread_create.

Correction — Use pthread_cancel to Terminate Threads

One possible correction is to use the pthread_cancel function. The pthread_cancel terminates a thread specified by its first argument at a specific cancellation point or immediately, depending on the thread's cancellation type.

#include <signal.h>
#include <pthread.h>

void* func(void *foo) {
  /* Execution of thread */
}
 
int main(void) {
  int result;
  pthread_t thread;
 
  if ((result = pthread_create(&thread, NULL, func, 0)) != 0) {
    /* Handle Error */
  }
  if ((result = pthread_cancel(thread)) != 0) {
    /* Handle Error */
  }
 
  /* Continue executing */
 
  return 0;
}

See also:

  • pthread_cancel for more information on cancellation types.

  • Pthreads for functions that are allowed to be cancellation points.

Result Information

Group: Concurrency
Language: C | C++
Default: Off
Command-Line Syntax: THREAD_KILLED_WITH_SIGNAL
Impact: Low

Version History

Introduced in R2018b