0

I am trying to modify the following code to use sigaction() to intercept SIGINT;

I need to replace the "for" loop with "while ( 1 ); you should be able to quit the program by entering "^\". (Need to intercept SIGQUIT.)

#include <signal.h>
#include <unistd.h>
#include <iostream>

using namespace std;

void func ( int sig )
{
     cout << "Oops! -- I got a signal " << sig << endl;
}

int main()
{
    (void) signal ( SIGINT, func ); //catch terminal interrupts

    //for ( int i = 0; i < 20; ++i )
    while(1) 
    {
         cout << "signals" << endl;
         sleep ( 1 ); 
    }
    return 0;
}
too honest for this site
  • 12,050
  • 4
  • 30
  • 52
  • 1
    SIGINT or SIGQUIT? Which one is it? – Kerrek SB Jan 27 '17 at 01:02
  • You need to set up the `struct sigaction` variable with the correct information. You then call `sigaction()` instead of `signal()`. Most of the rest remains unchanged. Note that invoking `cout << …` in a signal handler is very likely to be 'undefined behaviour. See [How to avoid using `printf()` in a signal handler](http://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler/). It's strictly for C, but similar concepts apply to C++ too. – Jonathan Leffler Jan 27 '17 at 01:14

1 Answers1

0

You can use sigaction to catch SIGINT (and still have the output you've described) with the following code (which compiles and works for me using clang on a Unix like OS):

#include <signal.h>
#include <iostream>
#include <unistd.h>

static int sigcaught = 0;

static void sighandler(int signum)
{
    sigcaught = signum;
}

int main()
{
    int signum = SIGINT;

    struct sigaction newact;
    struct sigaction oldact;
    newact.sa_handler = sighandler;
    sigemptyset(&newact.sa_mask);
    newact.sa_flags = 0;

    sigaction(signum, &newact, &oldact);

    while (!sigcaught)
    {
        std::cout << "waiting for signal" << std::endl;
        sleep(1);
    }
    std::cout << "Oops! -- I got a signal " << sigcaught << std::endl;
    return 0;
}

Please note that: this code intentionally isn't checking return values (like from sigaction nor sleep) since the original code isn't and since checking them may detract a reader from seeing the relevant differences. I would not want production code to ignore return values however (particularly those that can indicate errors).

Louis Langholtz
  • 2,913
  • 3
  • 17
  • 40