sigaction SIGINT,程序在 & (background) 中运行,没有得到信号
sigaction SIGINT, programm run in shell with & (background) doesn't get the signal
简单代码:
#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&
操作系统将控制权传递给外壳,我无法通过 CTRL+C 打破循环
我需要在 bash 脚本中运行此代码,我需要在后台运行它。在这种情况下,是否有可能以某种方式捕捉信号?
当您按ctrl-c
时,您将信号 2 (SIGINT) 发送到当前进程(在终端前台运行的进程)。您可以使用kill
将信号发送到在后台运行(以 & 开头)的进程:
$ kill -2 %%
当你说%%
时,你的意思是最后一个后台进程。当然,您可以指定另一个。你需要知道它的PID(参见ps(1))或JobID(bash(1)/jobs)。
我还想指出,您只能在具有作业管理的 shell 中使用 % 表示法(例如在 bash
中)。当您不在这样的外壳中时,您只能使用 PID。
上次启动的进程的 PID 在 $!
中。这在某些脚本中可能很有用。
相关文章:
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 运行时错误地址清理器:LEETCODE 中的致命信号
- 如何在长时间运行的方法中等待信号?
- 在绑定中捕获 fortran 运行时错误和信号C++
- 代码在我的系统中运行良好,但 coursera 自动评分器给了我未知的信号
- 在SIGABRT c ++信号之后继续运行程序
- 是信号处理程序,旨在无限期运行
- 运行时特性测试、setjmp、longjmp和信号掩码
- 在父母获得杀死信号和退出后,用system()产生的儿童进程继续运行
- 在通过ProcessBuilder运行的C程序中捕获信号
- 当将应用程序作为启动的守护程序运行时,C++ 库中的信号 10 (SIGBUS)
- 从Wt小部件信号事件运行popen()时出现问题
- sigaction SIGINT,程序在 & (background) 中运行,没有得到信号
- 在 QThread 中运行长时间操作并将信号发送到主线程仍会冻结 UI
- 运行时可用信号列表
- 如何克服运行时错误信号:25?等效地,浮点错误:核心转储
- 使用sigaltstack可以动态更改运行信号处理程序的堆栈
- 每次我在linux c++中为命名管道运行程序时,都会发出SIGSTOP信号
- 简单C++代码上的运行时错误信号11
- 如何在Qt中运行函数时断开所有信号