You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 8 Next »

Do not send an uncaught signal to a thread to terminate, because it kills the entire process as opposed to killing just the individual thread. This rule is a specific instance of SIG02-C. Avoid using signals to implement normal functionality.

Noncompliant Code Example

This code uses the pthread_kill() function to send a SIGKILL signal to the created thread. The thread receives the signal and the entire process is terminated.

int main(void){
  pthread_t thread;

  pthread_create(&thread, NULL, func, 0);
  pthread_kill(thread, SIGKILL);

  /* May continue executing briefly until the signal kills the process */

  return 0;
}

void func(void *foo){
  /* Execution of thread */
}

Compliant Solution

This code instead uses the pthread_cancel() to terminate the thread. The thread continues to run until it reaches a cancellation point. See the second referenced article for a list of functions that are cancellation points. If the cancellation type is set to asynchronous, the thread is terminated immediately. However, POSIX only requires the pthread_cancel(), pthread_setcancelstate(), and pthread_setcanceltype() functions to be async-cancel safe. An application that calls other POSIX functions with asynchronous cancellation enabled is non-conforming.

int main(void){
  pthread_t thread;

  pthread_create(&thread, NULL, func, (void*)0);
  pthread_cancel(thread);

  /* Continues */

  return 0;
}

void func(void *foo){
  /* Execution of thread */
}

Risk Assessment

Using signals as described has the simple consequence of terminating the process, which is clearly undesired. However there is no other direct risk.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

POS44-C

low

probable

low

P6

L2

References

[[OpenBSD]] signal() Man Page
http://www.mkssoftware.com/docs/man3/pthread_cancel.3.asp
http://www.opengroup.org/onlinepubs/007908799/xsh/threads.html

  • No labels