Until a signal is received?

So, I programmed in C recently and studied Signals and POSIX streams. I know that I can wait for a signal in a stream, but I was wondering if it has a stream that contains a while loop that will continue to run forever until SIGINT is received. Therefore, basically, I do not expect the signal (stopping the execution of the while loop), but continue to execute until the signal is received. Just listening to a specific signal.

I tried searching, but to no avail.

Any suggestions? Thanks in advance!

+4
source share
2 answers

How easy is it to use a simple signal handler?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

static void sigint_handler( int signum );
volatile static int done = 0;

int main( int argc, char *argv[] )
{
   if( signal( SIGINT, sigint_handler ) == SIG_ERR ) {
      perror( "signal()" );
      exit(1);
   }

   while( !done ) {
      (void)printf( "working...\n" );
      (void)sleep( 1 );
   }

   (void)printf( "got SIGINT\n" );

   return 0;
}

void sigint_handler( int signum )
{ done = 1; }

: done , , . . , .

+3

, sigtimedwait() .

SIGINT. , SIGINT :

sigset_t sigint_set;

sigemptyset(&sigint_set);
sigaddset(&sigint_set, SIGINT);    
sigprocmask(SIG_BLOCK, &sigint_set, NULL);

, SIGINT:

sigset_t sigint_set;
siginfo_t info;
const struct timespec zero_timeout = { 0, 0 };

sigemptyset(&sigint_set);
sigaddset(&sigint_set, SIGINT);    

while (sigtimedwait(&sigint_set, &info, &zero_timeout) != SIGINT)
{
    /* Do something */
}
+2

All Articles