How do I detect shutdown/reboot from linux app [duplicate]
Asked Answered
G

1

2

I have an application written in C which runs as a daemon and needs to send something through RS232 when system is in shutdown or reboot state, and it needs to distinguish between these two. So my idea is: In my application script /etc/init.d/my_app in "stop" case of my script, I will run /sbin/runlevel command to get current runlevel: 0 - shutdown state 6 - reboot state then I will execute some command to inform my daemon which state is it, daemon will perform communication through rs, and then will exit.

I think it should work, however it may not be the best solution, especially because my app is already running as a daemon, maybe I can receive some signal directly from system/kernel/library or through unix socket or something.

Best regards

Marek

Gesellschaft answered 9/10, 2013 at 10:43 Comment(0)
H
1

I am not sure which signal is send to an application on system shutdown. My best guess is SIGTERM and if the application does not shutdown SIGKILL. So did you try to catch SIGTERM and properly shut down your program? There are a lot of examples on the net how to do that.

For more sophisticated process handling you can send SIGUSR1, SIGUSR2 to your application.

Hodeida answered 9/10, 2013 at 11:54 Comment(2)
Yes I'm aware of SIGTERM and SIGKILL signals, I was also handling SIGUSR1 and SIGUSR2, but none of these answer my needs. SIGTERM and SIGKILL does not implicate that system is going down for reboot or halt. And SIGUSR1 or SIGUSR2 I can use to signal my app, for instance from /etc/init.d/my_script during execution of "stop" case.Gesellschaft
In case someone need it: When system is going down for reboot or shutdown, init sets variable $RUNLEVEL, that can be read in /etc/init.d/my_script during execution of "stop" case, and proper action can be executed eg. by sending SIGUSR1 to running application.Gesellschaft

© 2022 - 2024 — McMap. All rights reserved.