Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
865 views
in Technique[技术] by (71.8m points)

c - how to detect Linux shutdown/reboot

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.

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.

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

Thanks.

[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, '', 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);
}

[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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your assumptions are mistaken. There is no way to catch SIGKILL; it terminates the process with no chance to respond to it.

With that said, I may have a solution: you can catch SIGTERM, and if you install the signal handler with sigaction and the SA_SIGINFO flag, you should be able to determine which process sent you the SIGTERM signal. If it came from init (pid 1), it's a shutdown. This is mildly hackish but might work for your purposes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...