Sending a uncaught signal to a thread to terminate it should be avoided, as it kills the entire process as opposed to killing just the individual thread.
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(int argc, char* argv[]){ pthread_t thread; pthread_create(&thread, NULL, func, 0); pthread_kill(thread, SIGKILL); /* May run a few more lines 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. In the thread function we set the cancel type to asynchronous, so as to ensure an immediate cancel. If desired, the cancel type can be left as the default type of deferred, where the thread will not terminate until it reaches a cancellation point.
int main(int argc, char* argv[]){ pthread_t thread; pthread_create(&thread, NULL, func, (void*)0); sleep(1); pthread_cancel(thread); /* Continues */ return 0; } void func(void *foo){ pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); /* 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