如何检测Linux关闭/重新启动 [英] how to detect Linux shutdown/reboot

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

问题描述

我正在尝试在我的c程序中检测从Linux关闭或重新启动. 我发现程序可以使用signal(SIGTERM,handler)(SIGKILL,handler). 但是,如果用户也使用命令杀死该进程,则这两个触发器也会触发.

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);
}

[更新] 最后,我使用David Schwartz runlevel(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文件以获取运行级别.请参阅runlevel(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天全站免登陆