Last active
November 1, 2023 04:22
-
-
Save link89/c83c10c9f6380ada80d02b0ee59d3583 to your computer and use it in GitHub Desktop.
bash script to kill a process if no output for 60 seconds (feat. ChatGPT)
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 | |
# This script runs a command and kills it if there is no output for a certain time | |
# Define the command to run and the output file | |
COMMAND="lmp_mpi -in input.lmp" | |
OUTPUT_FILE="lammps.log" | |
# Define the timeout value in seconds | |
TIMEOUT=60 | |
# Run the command and redirect the output to the output file | |
$COMMAND > $OUTPUT_FILE & | |
# Get the process ID of the command | |
PID=$! | |
# Loop until the process is killed or exits normally | |
while kill -0 $PID 2>/dev/null; do | |
# Wait for the output file to be modified or timeout | |
inotifywait -e modify -t $TIMEOUT $OUTPUT_FILE >/dev/null 2>&1 | |
# Check the exit status of inotifywait | |
STATUS=$? | |
# If the status is 2, it means no change occurred within the timeout | |
if [ $STATUS -eq 2 ]; then | |
# Kill the process with SIGTERM | |
kill -TERM $PID | |
# Print a message to stderr | |
echo "Process killed due to no output for $TIMEOUT seconds" >&2 | |
# Break the loop | |
break | |
fi | |
done | |
# Wait for the process to terminate and get its exit code | |
wait $PID | |
EXIT_CODE=$? | |
# Print a message to stderr if the process exited abnormally | |
if [ $EXIT_CODE -ne 0 ]; then | |
echo "Process exited with code $EXIT_CODE" >&2 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment