RajSanpui
RajSanpui

Reputation: 12054

Why thread function not invoking? ( SIGEV_THREAD )

I have a program where i invoke a signal sigkill(getpid(), SIGUSR1). I wish when the signal comes, instead of the signal handler the thread function should be invoked, or both. For this i have populated the sigev_notify with SIGEV_THREAD.

But unfortunately, the thread function is not called. Why is it so?

Here is the code below:

#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <string.h>

static void ThreadhandlerTimer1(int);
void sig_handlerTimer1(int);

static void threadFunction(union sigval sv) // Should be invoked on receipt of signal "SIGEV_THREAD"
{
  printf("Thread function invoked");
}

int main()
{
    int i;
    static struct sigaction sa;
    static struct sigevent sevp;  

    memset (&sevp, 0, sizeof (struct sigevent));
    sevp.sigev_value.sival_ptr = NULL;
    sevp.sigev_notify = SIGEV_THREAD;
    sevp.sigev_notify_attributes = NULL;
    sevp.sigev_signo = SIGUSR1;
    sevp.sigev_notify_function=threadFunction;

    /* Setting the signal handlers */

    sa.sa_handler = sig_handlerTimer1;
    sa.sa_flags = 0;
    sigaction(SIGUSR1, &sa, NULL);

    for(i=0; i<10; i++)
    {
            if((i==3) || (i==6)){
              kill(getpid(), SIGUSR1);
            }

            printf("%d\n",i);
            sleep(1);
     }
    }

    void sig_handlerTimer1(int signum)
    {
      printf("Caught signal: %d\n",signum);
    }

Upvotes: 2

Views: 3178

Answers (2)

Barun Parichha
Barun Parichha

Reputation: 21

From your code, it seems you have just assigned values to sigevent, instead of using any where in code.

static struct sigevent sevp;

memset (&sevp, 0, sizeof (struct sigevent));
sevp.sigev_value.sival_ptr = NULL;
sevp.sigev_notify = SIGEV_THREAD;
sevp.sigev_notify_attributes = NULL;
sevp.sigev_signo = SIGUSR1;
sevp.sigev_notify_function=threadFunction;

To invoke threadFunction, call this from your signal handler.

> void sig_handlerTimer1(int signum)
> {
>  printf("Caught signal: %d\n",signum);
>  threadFunction(signum);
> }

If you want to use sevp, use something like timer_create() and timer_settime(). Check this link: http://ptgmedia.pearsoncmg.com/images/0201633922/sourcecode/sigev_thread.c

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249093

According to this documentation, the sigevent structure is only supported by "Some signal-generating functions, such as high-resolution timer expiration, asynchronous I/O completion, interprocess message arrival, and the sigqueue() function."

I don't know what your real plan for this code is (maybe you can tell us), but as it is, you are raising the signal directly which probably is not one of the supported cases for using SIGEV. If this code is fairly close to what you want in production you could simply call sigqueue() instead of kill() and it may just work.

Upvotes: 2

Related Questions