Search code examples
c++signalssigaction

How to call sigaction from C++


I know how to use it in C (with signal.h), but the <csignal> library is provided in C++ and I want to know if it includes sigaction? I tried running it but it said not found. I was wondering if I did something wrong?

#include <iostream>
#include <string>
#include <cstdio>
#include <csignal>

namespace {
  volatile bool quitok = false;
  void handle_break(int a) {
    if (a == SIGINT) quitok = true;
  }
  std::sigaction sigbreak;
  sigbreak.sa_handler = &handle_break;
  sigbreak.sa_mask = 0;
  sigbreak.sa_flags = 0;
  if (std::sigaction(SIGINT, &sigbreak, NULL) != 0) std::perror("sigaction");
}

int main () {
  std::string line = "";
  while (!::quitok) {
    std::getline(std::cin, line);
    std::cout << line << std::endl;
  }
}

But for some reason it doesn't work. EDIT: By "doesn't work", I mean the compiler fails and says there's no std::sigaction function or struct.

sigaction is C POSIX isn't it?


Solution

  • sigaction is in POSIX, not the C++ standard, and it's in the global namespace. You'll also need the struct keyword to differentiate between sigaction, the struct, and sigaction, the function. Finally, the initialization code will need to be in a function -- you can't have it in file scope.

    #include <cstdio>
    #include <signal.h>
    
    namespace {
      volatile sig_atomic_t quitok = false;
      void handle_break(int a) {
        if (a == SIGINT) quitok = true;
      }
    }
    
    int main () {
      struct sigaction sigbreak;
      sigbreak.sa_handler = &handle_break;
      sigemptyset(&sigbreak.sa_mask);
      sigbreak.sa_flags = 0;
      if (sigaction(SIGINT, &sigbreak, NULL) != 0) std::perror("sigaction");
      //...
    }