-1

I have a python-script that is started at bootup-time as a cronjob to collect measurement-data: @reboot python /path/to/my_script.py

The Linux-machine is rebooted daily at a certain time as a cronjob: 57 23 * * * sudo reboot

At the time of the reboot I would still have measurement-data that has not been saved yet and which needs to be transferred to a website which may take a couple of seconds. From what I see the reboot- or the shutdown-command would give some advance-warning for gracefully shutting down, however I have not found a way to catch that. Up to now I was experimenting with signal.SIGTERM, signal.SIGHUP but these don't cut it and don't react to the shutdown-command. Also trying with nohup did not yield the desired result.

Any advice on how to detect the time before shutdown in that Python-script? Cheers ye_ol_man

ye_ol_man
  • 37
  • 6
  • The [`atexit`](https://docs.python.org/3/library/atexit.html) module *might* be the simplest way to do what you're asking. – RoadieRich Mar 03 '22 at 20:46
  • Unfortunately not. `atexit` reacts when I stop the script itself but when I do a `reboot `then I don't see the registered handler executed. – ye_ol_man Mar 03 '22 at 21:08

1 Answers1

0

I was trying several approaches up to now and trying to detect the shutdown itself on the script from the cronjob did not really yield any positive results. To get the detection of shutdown I now found this viable workaround:

  • Have the worker-script started normally an boot-up of the RPi
  • In the worker-script detect the USER1-signal
  • when USE1-signal is detected the worker-script goes into shutdown
  • instead of just rebooting in the crontab I start a separate python-script, detect the PID of my worker-script and send the USR1-signal.
import os
import signal
import sys

search_file=sys.argv[1] #name of the script which should be searched for
print(search_file)

output=os.popen('pgrep -f ' + search_file)
my_pid=output.read()
line_pos=my_pid.find('\n') # two PIDs are detected, target-PID and PID of this script
my_pid=int(my_pid[:line_pos]) #first PID is target-PID
print(my_pid)
os.kill(my_pid, signal.SIGUSR1) # os.kill sends the various signals, e.g. SIGUSR1 to PID

This is not wanted initially but works. 8o)

ye_ol_man
  • 37
  • 6