Created
December 21, 2024 01:19
-
-
Save sleekweasel/270dd1ce6f8a830de20c89d661997750 to your computer and use it in GitHub Desktop.
bash-based mutex sort of thing, for MacOS which doesn't have flock or lockf or BASHPID
This file contains hidden or 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
#!/usr/bin/env bash | |
set +m # No noisy background report | |
( | |
set -m # New process group, please - It should survive teamcity finishing its step | |
( | |
PIDS=$HOME/lockpids | |
state=looking | |
while true ; do | |
t=$(mktemp -tpid); bash -c "while [[ -f $t ]] ; do sleep 1 ; done" & p=$(ps -p $! -o 'ppid=') ; rm $t | |
echo $p >>$PIDS | |
for i in $(cat $PIDS) ; do | |
if [[ "$i" -eq $p ]] ; then | |
echo $p > $PIDS.new ; mv $PIDS.new $PIDS | |
state=won | |
break | |
fi | |
if kill -0 $i 2>/dev/null ; then | |
[[ "$state" == "lost" ]] && exit | |
state=lost | |
break | |
fi | |
done | |
[[ "$state" = "won" ]] && break | |
sleep 1 # still looking or lost once | |
done | |
echo "PID $p is $state" | |
sleep 10 | |
echo "PID $p quits" | |
)& | |
)& |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment