Last active
August 23, 2017 22:15
-
-
Save darccio/ca06ed671ca56b548cae71b348417739 to your computer and use it in GitHub Desktop.
PID Shield: protect your commands against parallel execution
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 | |
## | |
## PID Shield: protect your commands against parallel execution | |
## | |
## Author: Dario Castañé <[email protected]> | |
## | |
## License: Public domain; do as you wish | |
## | |
pidshield() { | |
hash=$(echo -n "$@" | md5sum | cut -f1 -d' ') | |
filename="/tmp/psh-$hash-$(id -un).pid" | |
unset hash | |
if [ -f "$filename" ]; then | |
# Stale PID file check | |
running=$(pgrep -c --pidfile "$filename") | |
[ "$running" -eq 0 ] && rm -f "$filename" || exit 0 | |
unset running | |
fi | |
trap 'rm -f '"$filename" EXIT | |
echo $$ >"$filename" | |
unset filename | |
"$@" | |
bash -c "$(trap -p | grep -E "EXIT$" | sed "s/trap -- '//;s/' EXIT$//")" | |
trap - EXIT | |
} | |
## Usage: pidshield your_command --as usual | |
## Don't use it in your interactive shell, only in scripts. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment