通过调用atexit函数来终止一个程序(Linux)
Terminating a program with calling atexit functions (Linux)
是否有一种方法可以向进程(在Linux中)发送信号,从而在经过" atexit-function "后导致进程终止?(在这种情况下:void shutdownEngines()
)?使用"pkill name";
#include <cstdlib>
void shutdownEngines() {/*is not executed by "pkill name"*/}
int main() {
atexit(shutdownEngines);
while(true)
doStuff();
}
用法:我现在正在给一个机器人编程。每次我想测试它时,我会启动程序并以"结束它。pkill name
",但"shutdownEngines
";不被调用,机器人继续移动,从桌子上掉下来等。
我知道我能做到"pkill name; ./shutdownEngines.sh
",但在我的情况下,这将是非常糟糕的风格(连接到引擎的gpio引脚的数量是在主程序的头文件中定义的(主程序的源代码不在机器人上,而是在我的计算机上)。确保总是有一个"shutdownEngines.sh
";为每个机器人配置正确引脚的程序/脚本将非常复杂。
下面的代码工作得很好:
#include <iostream>
#include <csignal>
#include <cstdlib>
void signalHandler(__attribute__((unused)) const int signum) {
exit(EXIT_FAILURE);
}
void driverEpilog() {
std::cout << "shutting down engines...";
//drv255(0,0);
}
int main() {
signal(SIGTERM, signalHandler);
atexit(driverEpilog);
while(true)
system("sleep 1");
}
标题>从atexit
的手册页:
使用atexit()(和on_exit(3))注册的函数不会被调用如果进程异常终止,因为一个信号。
atexit
在主例程返回或调用exit
时调用,而不是在信号时调用。
当你呼叫pkill
时,你正在发送SIGTERM
信号。用signal
或sigaction
来处理这个信号(在SIGTERM
, SIGINT
, SIGFPE
,…上定义处理程序),在退出程序之前停止引擎。
示例摘自GNU C库文档:
void
termination_handler (int signum)
{
struct temp_file *p;
for (p = temp_file_list; p; p = p->next)
unlink (p->name); // don't delete files, stop your engines instead :)
}
int
main (void)
{
…
struct sigaction new_action, old_action;
/* Set up the structure to specify the new action. */
new_action.sa_handler = termination_handler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction (SIGINT, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN)
sigaction (SIGINT, &new_action, NULL);
sigaction (SIGHUP, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN)
sigaction (SIGHUP, &new_action, NULL);
sigaction (SIGTERM, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN)
sigaction (SIGTERM, &new_action, NULL);
…
}
(当然,没有处理程序可以处理SIGKILL
"信号",它告诉操作系统将您的进程从活动进程列表中删除,而无需进一步通知!)
相关文章:
- 如何检查第三个 API 是否在 Linux 中为 c/c++ 程序创建了一个新线程?
- 有没有办法让我编写一个可以在Windows和Linux上运行的命令行游戏?
- 我在使用 boost::serialization 时遇到了一个问题,我的代码在 Linux 中运行良好,但在 Wind
- 一个32位版本的应用程序,建立在CentOS 6 x64上,当在较新的Linux上启动时,在"dl_itera
- 如何在打开另一个图像时关闭图像 - linux c ++
- 如何交叉编译一个在 Linux for Linux 和 Linux for Windows 中编译的程序?
- 在 Ubuntu(linux OS)中将一个巨大的文件读入C++向量
- 如何在 C++ 中创建一个适用于 Windwos 和 Linux 的文件夹(目录)
- 您如何将所有链接依赖项都包装到一个Linux静态库中
- 调试从 Linux 中的另一个C++应用程序启动的 python 脚本
- 在 Linux 上编译一个 c++ 应用程序,并在 TI TIVA TM4C123GH6PM上刷新它
- 如何设置一个"precise"的定期计时器来监控Linux(C / C++)中的内容?
- 如何检测和与Linux下的另一个过程进行通信
- C++ 将目录复制到另一个目录(Linux cp 命令)
- 一个C++编译器是为不同的平台(Linux,Windows等)多次编写的,这是真的吗?
- 在 Linux 下的 Qt,如何检测一个进程已经在运行
- 如何使用C/C 系统调用来获取Linux过程中一个过程的当前大小
- Linux/GCC:是否有一种方法可以检查构建是否与其他机器上的前一个机器相同
- 是否对在另一个Linux发行版中使用G 编译的可执行文件有限制
- 杀死一个Linux进程,停止它在Oracle数据库中的查询工作吗?