gpt4 book ai didi

c++ - 覆盖 Ctrl-C

转载 作者:IT老高 更新时间:2023-10-28 23:19:05 24 4
gpt4 key购买 nike

我应该覆盖 CtrlC 信号并使用它来打印消息。它不应该结束程序。

到目前为止发生的情况是,当按下 CtrlC 时,它会打印消息,但会结束程序。

当我问我的教授时,他告诉我这样做:您需要让您的信号处理程序不再继续处理信号。现在信号正在由您的代码处理,然后转到父处理程序。

是否有我应该添加的方法或者我需要将信号安装程序移动到某个地方?

这是我目前的代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include "Input.h"
#include "CircleBuff.h"

//void handler_function(int signal_id);

void catch_int(int sig_num){

//reset the signal handler again to catch_int, for next time
signal(SIGINT, catch_int);
//print message
printf("Print History");
fflush(stdout);
}

void printHistory(CircleBuff hist){
cout << "Complete History:\n" << endl;
hist.print();
cout << endl;
}

int main(int argc, char** argv){

struct sigaction signal_action; /* define table */
signal_action.sa_handler = catch_int; /* insert handler function */
signal_action.sa_flags = 0; /* init the flags field */
sigemptyset( &signal_action.sa_mask ); /* are no masked interrupts */
sigaction( SIGINT, &signal_action, NULL ); /* install the signal_action */

do{


//My code: where the value report will be assigned within.

} while(report != 1)

}

最佳答案

哇,方式太多代码无法筛选。但是,如果您使用 C 标准库,您应该获得所需的行为。这是一个 C++ 版本:

#include <iostream>
#include <csignal>

sig_atomic_t sigflag = 0;

void sighandler(int s)
{
// std::cerr << "Caught signal " << s << ".\n"; // this is undefined behaviour
sigflag = 1; // something like that
}

int main()
{
std::signal(SIGINT, sighandler);

// ... your program here ...

// example: baby's first loop (Ctrl-D to end)
char c;
while (std::cin >> c)
{
if (sigflag != 0) { std::cerr << "Signal!\n"; sigflag = 0; }
}
}

这将捕获 Ctrl-C(引发 SIGINT),并且不会替换信号处理程序,因此每次都会触发,并且没有人终止程序。

请注意,信号处理程序由 fork()ed 子代继承。

Posix 函数 sigaction() 允许您注册“一次性”处理程序,这些处理程序在被调用一次后被标准处理程序替换。不过,这更高级且特定于 Posix。

编辑: 正如@Dietrich 指出的那样,您永远不应该在信号处理程序内部做任何实际工作。相反,您应该设置一个标志(我提供了一个示例),并在循环中检查该标志(并在那里打印消息)。我也会为此修改示例。

关于c++ - 覆盖 Ctrl-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7623401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com