Last active
March 17, 2024 07:48
-
-
Save link89/930fc5ae3e33eb02fe28ad40521181dc to your computer and use it in GitHub Desktop.
a ffmpeg wrapper script to kill process when timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
trap 'echo ffmpegexit && pkill -P $$' EXIT SIGINT SIGTERM SIGHUP | |
# Define the timeout duration in seconds for file change | |
TIMEOUT_IN_S=10 | |
TOTAL_TIMEOUT_IN_S=7200 | |
# Get the last argument as the output file | |
OUTPUT_FILE="${@: -1}" | |
# Get the full path of the current script's directory | |
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" | |
# Start ffmpeg with a timeout and all the arguments in the background using the full path | |
timeout --foreground $TOTAL_TIMEOUT_IN_S "$SCRIPT_DIR/ffmpeg" "$@" & | |
FFMPEG_PID=$! | |
# Initialize the last modification time | |
LAST_MOD_TIME=$(date +%s) | |
# Monitor the output file | |
while true; do | |
# Get the current modification time | |
CURRENT_MOD_TIME=$(stat -c %Y "$OUTPUT_FILE" 2>/dev/null || echo $LAST_MOD_TIME) | |
# Check if the modification time has not changed | |
if [[ "$LAST_MOD_TIME" -eq "$CURRENT_MOD_TIME" ]]; then | |
# If the file hasn't changed for the specified timeout duration, terminate ffmpeg | |
if [[ $(($(date +%s) - LAST_MOD_TIME)) -ge $TIMEOUT_IN_S ]]; then | |
echo "ffmpeg error: timeout" | |
pkill -P $$ | |
exit 0 | |
fi | |
else | |
# Update the last modification time | |
LAST_MOD_TIME=$CURRENT_MOD_TIME | |
fi | |
# Wait for 1 second before checking again | |
sleep 5 | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment