【问题标题】:Cancel CTRL+C while system() is executing [C++]在 system() 执行时取消 CTRL+C [C++]
【发布时间】:2021-06-23 12:53:53
【问题描述】:

当我正在执行 system() 时,如何让 CTRL+C 不执行任何操作。

这是我的代码:

#include <iostream>
#include <functional>
#include <signal.h>
void noCTRLCCancel(int sig) {
    signal(SIGINT, noCTRLCCancel);
    std::cout << "CTRL+C pressed, not shutting down." << std::endl;
}
inline void command() {
    system("some command"); // When CTRL+C is pressed, it cancels the command, but how to cancel CTRL+C and do nothing?
}
int main(int argc, char **argv) {
    signal(SIGINT, noCTRLCCancel);
    command();
}

【问题讨论】:

  • 您也可以正确打开进程(使用popenCreateProcess 或围绕它们的包装器)。如果可能的话,应该避免只使用system
  • 我的项目需要用到它,所以是的,我用system()就对了

标签: c++ ctrl


【解决方案1】:

您可以使用 SIG_IGN 忽略特定信号,并使用 SIG_DFL 将其设置回默认值。

void command() {
    std::signal(SIGINT, SIG_IGN);
    system("some command");
    std::signal(SIGINT, SIG_DFL);
}

https://en.cppreference.com/w/cpp/utility/program/signal

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多