a_user
a_user

Reputation: 213

Two signals in the same main

I want to use two signals in the same main. So I made two handlers etc. That's my code:

volatile sig_atomic_t go_on = 0;
volatile sig_atomic_t execute = 0;

void sig_syn(int sig_no)
{
    go_on = 1;
}

void exe_handler(int sig_no)
{
    execute = 1;
}

struct sigaction action;
sigset_t mask;

struct sigaction e_action;
sigset_t e_mask;

sigfillset (&mask);
action.sa_handler = sig_syn;
action.sa_mask = mask;
action.sa_flags = 0;
sigaction (SIGRTMIN, &action, NULL);

sigfillset (&e_mask);
e_action.sa_handler = exe_handler;
e_action.sa_mask = e_mask;
e_action.sa_flags = 0;
sigaction (SIGRTMIN, &e_action, NULL);

while(go_on == 0){}         
go_on = 0;
.
.
.

while(execute == 0){}
execute = 0;
.
.
.

Is it correct that i use all these two times? The reason I ask is because my program doesn't run but no errors appear... Any help? Thanks in advance!

Upvotes: 0

Views: 98

Answers (1)

Cristiano Araujo
Cristiano Araujo

Reputation: 1962

First of all, if your program doesn't run try out putting some debugging, gdb would be better, but printfs can do the job.

A Unix program can receive a lot of signals, checkout "man signal" to the usage and "man 7 signal" to all signals.

I'written and tested the following code.

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
void
termination_handler (int signum)
{
    printf("Signal %d\n",signum);
    exit(0);
}

int signal1 = 0;

void
usr_signal1(int signum)
{
    printf("Signal 1 received\n");
    signal1 = 1;
}


int signal2 = 0;

void
usr_signal2(int signum)
{
    printf("Signal 2 received\n");
    signal2 = 1;
}


int
main (void)
{
    printf("My pid is : %d\n",getpid());
    if (signal (SIGTERM, termination_handler) == SIG_IGN)
        signal (SIGTERM, SIG_IGN);
    if (signal (SIGUSR1, usr_signal1) == SIG_IGN)
        signal(SIGUSR1, SIG_IGN);
    if (signal (SIGUSR2, usr_signal2) == SIG_IGN)
        signal(SIGUSR2, SIG_IGN);
    printf("Main has started\n");

    while(0 == signal1) { sleep(1); };

    printf("Main moved to stade 1 \n");

    while(0 == signal2) { sleep(1); };

    printf("Main moved to stade 2 \n");
    printf("Main is done ! \n");

    return 0;
}

After compiling and running, it will print it's pid and keep waiting signals SIGUSR1 and SIGUSR2.

$ ./main 
My pid is : 6365
Main has started
Signal 1 received
Main moved to stade 1 
Signal 2 received
Main moved to stade 2 
Main is done ! 

Sending the kills with

kill -10 6365
kill -12 6365

works.

Upvotes: 1

Related Questions