简单代码:
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
using namespaces td;
bool unblock = false;
long int ile = 0;
void ouch(int sig) {
cout << "signal " << sig << endl;
unblock = true;
}
int main(){
struct sigaction act;
act.sa_handler = ouch;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGINT, &act, 0);
do {
cout << "." << endl;
} while(!unblock);
cout << "EXIT" << endl;
}
现在我编译代码并得到“a.out”。 当我像这样运行 a.out 时:
[przemek@localhost test]$ ./a,out
它按预期运行,当我按 CTRL+C 时程序按需要退出 但是当我像这样运行程序时(我的项目需要):
[przemek@localhost test]$ ./a.out&
操作系统将控制传递给 shell,我无法通过 CTRL+C 打破循环
我需要在 bash 脚本中运行此代码,并且需要在后台运行它。在这种情况下是否有可能以某种方式捕捉到信号?
最佳答案
当您按下 ctrl-c
时,您会向当前进程(在终端前台运行的进程)发送信号 2 (SIGINT)。您可以使用 kill
将信号发送到在后台运行的进程(以 & 启动):
$ kill -2 %%
当您说%%
时,您指的是最后一个后台进程。当然你可以指定另一个。您需要知道它的 PID(请参阅 ps(1))或 JobID(bash(1)/jobs)。
我还想指出,您只能在具有作业管理功能的 shell 中使用 %-notation(例如,在 bash
中)。当您不在这样的 shell 中时,您只能使用 PID。
最后启动的进程的 PID 在 $!
中。这在某些脚本中可能很有用。
关于c++ - sigaction SIGINT,程序在 shell 中运行 &(背景)没有得到信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11084814/