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

Compare with Current View Page History

« Previous Version 6 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 in most cases it is not safe to do so, and should be generally avoided.

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

  • No labels