How to call sigaction from C++
Asked Answered
D

1

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?

Doy answered 19/8, 2018 at 18:3 Comment(4)
sigaction is not part of Standard C++, so wheter you can use it is down to your implementationBlain
Unrelated: volatile bool may not be good enough. More on that: set flag in signal handlerEmulsify
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? ...Polyhydric
"but it said not found" What wasn't found? What said it?Polyhydric
M
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");
  //...
}
Mingy answered 19/8, 2018 at 18:18 Comment(4)
Should I use the implementation in <signal.h> or namespaced one in <csignal>?Doy
@AidenWoodruff signal.h is guaranteed to have it on a POSIX plaftorm. I don't think that's true for <csignal>.Mingy
why quitok is declared in an unnamed namespace?Gourmand
@SaeidYazdani AFAIK, it should have the same effect as declaring each of the such-enclosed declarations as static.Mingy

© 2022 - 2024 — McMap. All rights reserved.