1

I'm working on a project that among others uses the camera to record a video to an USB stick as soon as Pi turns on. I made the Pi shut down via a GPIO pin via a small script and I was wondering, is there a way to stop the camera recording when the command to safely shutdown is issued? I want to do this to prevent the USB stick from being corrupted if I shut down Pi while it's writing to it.

Below is the python code and the .sh for safe sutdown. The camera script is a simple file with camera.start_recording

  #!/usr/bin/env python


    import RPi.GPIO as GPIO
    import subprocess

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.wait_for_edge(21, GPIO.FALLING)

    subprocess.call(['shutdown', '-h', 'now'], shell=False)

and the .sh file

    #! /bin/sh

    ### BEGIN INIT INFO
    # Provides:          shutdown.py
    # Required-Start:    $remote_fs $syslog
    # Required-Stop:     $remote_fs $syslog
    # Default-Start:     2 3 4 5
    # Default-Stop:      0 1 6
    ### END INIT INFO

    # If you want a command to always run, put it here

    # Carry out specific functions when asked to by the system
    case "$1" in
      start)
        echo "Starting shutdown.py"
        /usr/local/bin/shutdown.py &
        ;;
      stop)
        echo "Stopping shutdown.py"
        pkill -f /usr/local/bin/shutdown.py
        ;;
      *)
        echo "Usage: /etc/init.d/shutdown.sh {start|stop}"
        exit 1
        ;;
    esac

exit 0

1 Answer 1

3

Shutdown on Linux works the following way:

  • All services are stopped in the reverse (or some similiar "reversed") order they were started at boot.
  • All other processes recieve the SIGTERM signal and shall shutdown themselves.
  • Wait a few seconds for them to actually do this.
  • All remaining processes "recieve" the SIGKILL signal (Linux itself kills them, SIGKILL cannot be ignored).
  • Filesystems get unmounted and synced.

The safest way to handle this would be writing service files for your software (aka systemd units). The second safest way would be understanding the default behaviour of all software in the face of SIGTERM (Python itself, raspivid, raspistill etc). The third option would be to catch the SIGTERM with a "signal handler" you wrote itself. Python allows you to simply catch all interesting signals and act upon them easily (except SIGKILL, of course)

1
  • Also worth noting is that the filesystem on the USB will be unmounted during a proper shutdown, and if it cannot be because it is in use by a process, there will be an error logged (and likely a delay waiting for the process to die properly so the fs can be unmounted).
    – goldilocks
    Commented Jun 18, 2018 at 19:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.