简体   繁体   English

如何从C ++调用sigaction

[英]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? 我知道如何在C(与signal.h)中一起使用它,但是<csignal>库在C ++中提供,我想知道它是否包含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. 编辑:“不起作用”是指编译器失败,并说没有std :: sigaction函数或结构。

sigaction is C POSIX isn't it? 这是C POSIX吗?

sigaction is in POSIX, not the C++ standard, and it's in the global namespace. sigaction在POSIX中,而不是C ++标准中,并且在全局名称空间中。 You'll also need the struct keyword to differentiate between sigaction , the struct, and sigaction , the function. 您还需要struct关键字来区分sigactionsigaction函数。 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");
  //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM