gpt4 book ai didi

c - 段错误信号处理程序 signint

转载 作者:行者123 更新时间:2023-11-30 17:03:13 26 4
gpt4 key购买 nike

我正在 try catch SIGINT (CTRL + C)。我希望当用户输入 CTRL + C 时,它将杀死子进程,但父进程将正常继续。当我的程序中有子进程时,它工作正常,但是当我没有子进程时,我会得到“段错误”。

我已经这样做了:

void sig_handler(int signo);
//========================================
int main()
{
// CTRL + C => SIGINT handler
struct sigaction act;
act.sa_handler = sig_handler;
sigfillset(&act.sa_mask);
act.sa_flags = 0;

// Catch the signal
sigaction(SIGINT, &act, NULL);
...
// done some checks and then fork a child.
}

// SIGINT handler
void sig_handler(int signo)
{
// dont know what to write here
}

最佳答案

我相信只要使用 sigset() 你就可以实现你的目标。

我会引用 sigset 手册页中的一些信息。

The sigset() function modifies signal dispositions. The sig argument specifies the signal, which may be any signal except SIGKILL and SIGSTOP. The disp argument specifies the signal's disposition, which may be SIG_DFL, SIG_IGN, or the address of a signal handler. If sigset() is used, and disp is the address of a signal handler, the system adds sig to the signal mask of the calling process before executing the signal handler; when the signal handler returns, the system restores the signal mask of the calling process to its state prior to the delivery of the signal. In addition, if sigset() is used, and disp is equal to SIG_HOLD, sig is added to the signal mask of the calling process and sig 's disposition remains unchanged. If sigset() is used, and disp is not equal to SIG_HOLD, sig is removed from the signal mask of the calling process.

引用此链接:sighold, sigignore, sigpause, sigrelse, sigset — legacy interface for signal management

您可以建立一个处理函数,当您收到 SIGINT 时将调用该函数。

void handler(int signo){
// Here you can kill the child, if it exists
}

int main(int argc, char *argv[])
{
...
sigset(SIGINT, handler);
...
}

希望对您有帮助,如果您需要更多帮助,请在评论中提及。

关于c - 段错误信号处理程序 signint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242130/

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