Skip to content

Instantly share code, notes, and snippets.

@kfiresmith
Created August 30, 2024 19:53
Show Gist options
  • Save kfiresmith/f553bab0bad409166e2f34eec91e5bbd to your computer and use it in GitHub Desktop.
Save kfiresmith/f553bab0bad409166e2f34eec91e5bbd to your computer and use it in GitHub Desktop.

Revisions

  1. kfiresmith created this gist Aug 30, 2024.
    39 changes: 39 additions & 0 deletions demonstrate-pidfile-management.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    #!/bin/bash


    # Obtain the name of the script dynamically so that we can re-use this code block on any script
    SCRIPT_FULLNAME="${0##*/}"
    # Trim off the file extension if one is present
    SCRIPT_TRIMMEDNAME="${SCRIPT_FULLNAME%.*}"

    # /run is superior to /tmp, but we can't write a lock file there if we aren't root.
    # We want to maintain the option of using this code block in scripts not run by root,
    # so we fall back to using good old /tmp
    LOCK_DIR="/run"
    [ -w "$LOCK_DIR" ] || LOCK_DIR="/tmp"
    LOCK_FILE="$LOCK_DIR/$SCRIPT_TRIMMEDNAME.lock"

    # Function to remove the lock file on exit
    cleanup() {
    rm -f "$LOCK_FILE"
    }
    # Trap to ensure PID file is removed even if the script is interrupted
    # This runs on exit whether the script was successful, failed, or interrupted.
    trap cleanup EXIT

    # Check if the PID file exists. If it already exists, we just exit so that we don't
    # create a cron pileup by re-running the running script again over itself.
    if [ -e "$LOCK_FILE" ]; then
    echo "Script is already running. Exiting."
    exit 1
    fi

    # If we've made it this far, write the current PID to the PID file. Now we can
    # proceed with running the actual script
    echo $$ > "$LOCK_FILE"

    # Do stuff below


    # Remove the PID file (handled by the trap)
    exit 0