5

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?

Aiden Woodruff
  • 341
  • 3
  • 9
  • 1
    sigaction is not part of Standard C++, so wheter you can use it is down to your implementation –  Aug 19 '18 at 18:05
  • Unrelated: `volatile bool` may not be good enough. More on that: [set flag in signal handler](https://stackoverflow.com/questions/18907477/set-flag-in-signal-handler) – user4581301 Aug 19 '18 at 18:09
  • Describe "But for some reason it doesn't work." in more detail. Does it not compile? Does the signal not get handled? Does the program crash? ... – eerorika Aug 19 '18 at 18:15
  • "but it said not found" *What* wasn't found? *What* said it? – eerorika Aug 19 '18 at 18:16

1 Answers1

6

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");
  //...
}
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142