user2203774
user2203774

Reputation: 619

How can I display the output for sigusr1 and sigusr2?

I am a beginner in C and system programming. I wrote a program and it should display the following: Caught SIGUSR1 Caught SIGUSR2 Caught SIGINT

However, when I do "./test.c", the only thing I see is "Caught SIGINT" when I type Ctrl-C. How can I fix my code so my program displays the messages above? Sorry if my question is dumb. Your help is greatly appreciated. Thanks for reading.

EDITED:

#include <signal.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

static void sigHandler_sigusr1(int sig)
{
    //sig contains the signal number that was received
    printf("Caught SIGUSR1, %d\n", getpid());
    //kill(getpid(), SIGUSR1);
}

static void sigHandler_sigusr2(int sig)
{
    //sig contains the signal number that was received
    printf("Caught SIGSR2, %d\n", getpid());
    //kill(getpid(), SIGUSR2);
}

static void sigHandler_sigint(int sig)
{
    //sig contains the signal number that was received
    printf("Caught SIGINT, Existing, %d\n", getpid());
    //kill(getpid(), SIGINT);
    exit(EXIT_SUCCESS);
}

int main(int argc, char *argv[])
{

    if (signal(SIGUSR1, sigHandler_sigusr1) == SIG_ERR)
        printf("Unable to create handler for SIGUSR1\n");

    if (signal(SIGUSR2, sigHandler_sigusr2) == SIG_ERR)
        printf("Unable to create handler for SIGUSR2\n");

    if (signal(SIGINT, sigHandler_sigint) == SIG_ERR)
        printf("Unable to create handler for SIGINT\n");

    kill(getpid(), SIGUSR1);
    kill(getpid(), SIGUSR2);
    kill(getpid(), SIGINT);

    while (1)
    {
        sleep(1);
    }

    return 0;
}

Upvotes: 2

Views: 3438

Answers (3)

Scotty Bauer
Scotty Bauer

Reputation: 1277

That all looks good.

With SIGUSR's you have to explicitly call them in the program. You can't trigger them with ctrl-z or ctrl-c.

You didn't show any code where you try and trigger the signals.

Upvotes: 1

Ran Eldan
Ran Eldan

Reputation: 1350

In order to active the signal handler function you need to send signal to the procces. It is missing from your code.

This is how you send signal to yourself:

kill(getpid(), SIGUSR1);

You need to do it for SIGUSR1 and SIGUSR2.

The reason you can see SIGINT message is that when you press ctrl+c you actually sending a SIGINT singal to your procces.

Upvotes: 2

Fla&#235;ndil
Fla&#235;ndil

Reputation: 118

I can be wrong, but SIGUSR1 and SIGUSR2 are user specified signals.

When you do "Ctrl-C", you do an interrupt, caught by SIGINT handler.

In order to caught SIGUSR1 ans SIGUSR2 you have to throw them yourself :

kill(pid, SIGUSR1);

More informations

Upvotes: 1

Related Questions