BASH
Monitor and Restart a Background Process
Ensure critical background services (like Node.js apps or queue workers) stay running by checking their status and automatically restarting them if they're down.
#!/bin/bash
# A unique part of the process command line or name to monitor
PROCESS_IDENTIFIER="my_node_app.js"
# Full command to start the process if it's not running
# Ensure it's run in the background if intended, e.g., 'nohup' or '&'
START_COMMAND="nohup node /path/to/your/app/my_node_app.js > /dev/null 2>&1 &"
# Path to a log file for this script's actions
MONITOR_LOG="/var/log/process_monitor.log"
# Function to log messages with a timestamp
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$MONITOR_LOG"
}
# Check if the process is running using pgrep
if pgrep -f "$PROCESS_IDENTIFIER" > /dev/null
then
log_message "Process '$PROCESS_IDENTIFIER' is running."
else
log_message "Process '$PROCESS_IDENTIFIER' is NOT running. Attempting to restart..."
eval "$START_COMMAND"
# Give it a moment to start
sleep 5
if pgrep -f "$PROCESS_IDENTIFIER" > /dev/null
then
log_message "Process '$PROCESS_IDENTIFIER' restarted successfully."
else
log_message "Failed to restart process '$PROCESS_IDENTIFIER'. Check logs."
fi
fi
How it works: This script monitors a specific background process using `pgrep -f` (which searches process names and full command lines). If the process, identified by `PROCESS_IDENTIFIER`, is not found, the script attempts to restart it using the defined `START_COMMAND`. It includes basic logging to a `MONITOR_LOG` file to track its actions. This is commonly used in cron jobs to ensure continuous operation of critical services like API servers or queue workers.