如何检测Linux的关机/重启[解决] [英] how to detect Linux shutdown/reboot[solved]

查看:689
本文介绍了如何检测Linux的关机/重启[解决]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的C程序来检测关机或重启的Linux操作系统。
我发现,程序可以使用信号(SIGTERM,处理程序)(SIGKILL,处理程序)。
但是,如果用户杀死命令的过程中,也这两个将触发。

I'm trying to detect shut down or reboot from Linux in my c program. I found that program can use signal(SIGTERM, handler) (SIGKILL, handler). But these two will trigger if user kill the process with command, too.

目前的一些解决方案,他们说可以使用运行级别,但它不会工作。
不知道这个过程是杀系统初始化运行级别之前。
我甚至尝试把脚本rcx.d,但它仍然是行不通的。

At some solutions, they said can use runlevel but it won't work. Don't know if the process is kill before the system init the runlevel. I even try to put script in rcx.d, but it still won't work.

有没有人有一些建议?
我需要在多种Linux系统上运行。

Does anyone has some advise? I need to run on many kinds of Linux system.

感谢。

[更新]
我用R染料溶液,但我仍然没有看到我的数据是在重启或关机清楚。
它是我的职责是错误的?

[Update] I use R solution, but I still don't see my data were clear at reboot or shutdown. Is it my function is wrong??

int start() {
    if (initIni() == EXIT_FAILURE)
        return EXIT_FAILURE;
    struct sigaction act;
    memset(&act, '\0', sizeof(act));
    act.sa_sigaction = &signal_callback_handler;
    act.sa_flags = SA_SIGINFO;
    sigaction(SIGTERM, &act, NULL);
....
}

void signal_callback_handler(int signum, siginfo_t *siginfo, void *context) {
    if (signum == SIGTERM && (long)siginfo->si_pid == 1) {
        clearData();
    }
    exit(signum);
}

[更新]
最后,我用大卫·施瓦茨运行级别(8)例如解决我的问题。
如果你使用Linux命令的运行级别也不会有用。
感谢伟大的解决方案。

[Update] Finally, I use David Schwartz runlevel(8) example to solve my problem. It won't be useful if you use linux command runlevel. Thanks for the great solution.

推荐答案

捕捉SIGTERM。在处理程序,阅读的/ var / run / utmp文件文件,以获得运行级别。见的源$ C ​​$ C 运行级别(8)命令,以供参考。

Catch SIGTERM. In the handler, read the /var/run/utmp file to get the runlevel. See the source code of the runlevel(8) command for reference.

这篇关于如何检测Linux的关机/重启[解决]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆