How to use sigsuspend

I have this code, and I have to make the program block repeatedly waiting for a signal. My teacher wants us to use sigsuspend and masks instead of pause or sleep. I am not familiar with sigsuspend or mask, I know that sigsuspend () temporarily replaces the signal mask of the calling process with the mask given by the mask, and then pauses the process until the signal is delivered, the action of which is to call the signal handler or terminate the process. But how to implement it.

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

unsigned Conta = 0;

void mypause(int sign)
{
    switch (sign)
    {
        case SIGINT:
            printf("You've pressed ctrl-C\n");
            printf("I'm running waiting for a signal...\n");
            Conta++;
            break;

        case SIGQUIT:
            printf("You've pressd ctrl-\\n");
            printf("Number of times you've pressed CTRL-C: %d", Conta); 
            exit(0);
            break;
    }
}

int main()
{
    alarm(3);
    printf("I'm Alive\n");

    signal(SIGINT, mypause);
    signal(SIGQUIT, mypause);
    printf("I'm running, waiting for a signal...\n");
    while (1)
    {
    }

    return (0);
}
+5
source share
2 answers

A simple way to start is to simply call sigsuspendwith an empty mask (i.e. any signal can wake the program):

sigset_t myset;
(void) sigemptyset(&myset);
while (1) {
    (void) printf("I'm running, waiting for a signal...\n");
    (void) sigsuspend(&myset);
}

sigprocmask, (SIGINT SIGQUIT), , sigsuspend. " ", sigprocmask .

+8

GNU libc manual :

: int sigsuspend (const sigset_t * set)

, , , . , ​​ , , .

, , , sigsuspend .

, sigsuspend . sigsuspend , .

, .

sigsuspend - :

 sigset_t mask, oldmask;

 ...

 /* Set up the mask of signals to temporarily block. */
 sigemptyset (&mask);
 sigaddset (&mask, SIGUSR1);

 ...

 /* Wait for a signal to arrive. */
 sigprocmask (SIG_BLOCK, &mask, &oldmask);
 while (!usr_interrupt)
   sigsuspend (&oldmask);
 sigprocmask (SIG_UNBLOCK, &mask, NULL);

. , sigsuspend , , sigsuspend - SIGUSR1 . sigprocmask , .

: , while , , -, SIGUSR1 . , , sigsuspend, , , , . , usr_interrupt, "" .

, , . , , - .

+6

All Articles