Reputation: 158
I have a script that controls an array of 12v relays depending on certain paramters. For an example: I am monitoring temperatures and pressures. If a temperature exceeds a certain value a relay will be pulled in to open vents and start fans. If the temperature drops to a certain value the relays are released and the vents will close and the fans will stop. Same with the pressures, which will open a solenoid valve and close it again depending on the pressure values.
All works fine and I am happy. The script (bash) is started at boot-up. However, sometimes the script dies mysteriously which leaves the relays in an "active" state.
Is there a way to ensure to reset the relays to "not-active" or "unenergized" when the script dies?
Upvotes: 0
Views: 24
Reputation: 84662
Continuing from my comment, you can trap any of the signals your script can receive (except SIGKILL
and SIGSTOP
) that are shutting it down and use trap
to intercept the signal received and run the required commands to reset the relays to "not-active" or "unenergized" state before the process dies.
Using trap
is quite easy. You simply set a trap at the top of your script listing the commands to be executed when a signal is caught. For simply commands you can do
trap 'command1; command2` SIGTERM SIGINT EXIT
to run command1
and command2
on receipt of any of the three listed signals. If you have a series of commands you need to execute, declare a function and then have trap
execute the function on signal receipt, e.g.
cleanup () {
# any number of commands to run
}
trap cleanup SIGTERM SIGINT EXIT
See man 7 signals
for addition information on standard signals. Consult man bash
(or search on "using trap in bash") for additional information on trap
.
Upvotes: 2