rameshrgtvl rameshrgtvl - 11 days ago 5
C Question

Linux : pthread_cond_signal() is not working inside a Signal Handler()

Summary
-----------
1. In main() am going for pthread_cond_wait().
2. In signal handler() am waking main() using pthread_cond_signal().
3. But main() is not coming out from pthread_cond_wait().


What is wrong here? help me out.

#include <stdio.h>
myclass *myObj = NULL;


In main I am trying to wait for a signal:

int main()
{
myObj = new myclass;
/* do something */
myobj->gotoWait(); <=== Wait blocked for ever.
/* do clean up here */
return 0;
}


Signal handler sending a signal to main thread:

static void signalHandler(int sig, siginfo_t *siginfo, void *context)
{
myObj->wakeFromWait();
}


Actual class implementing the waiting for and sending of signals.

What is wrong here?

myclass::gotoWait()
{
pthread_mutex_lock(&mtx);
pthread_cond_wait(&cnd, &mtx);
pthread_mutex_unlock(&mtx);
}
myclass::wakeFromWait()
{
pthread_mutex_lock(&mtx);
pthread_cond_signal(&cnd, &mtx);
pthread_mutex_unlock(&mtx);
}

Answer

In Signal handler there are only a very limited number of syscalls allowed.

see man 7 signal

http://man7.org/linux/man-pages/man7/signal.7.html

My Suggestion is, to be on the safe side, the so called "self pipe trick". http://man7.org/tlpi/code/online/diff/altio/self_pipe.c.html

You could start a thread which runs a select Loop on the self pipe and call your appropiate handler.

What is wrong in your code? You are locking a mutex inside the Signal handler

EDIT: Here there is a guide for signals http://beej.us/guide/bgipc/output/html/multipage/signals.html