Created
March 15, 2019 08:26
-
-
Save beyu/462241bd73ae630cd7ee937a90766046 to your computer and use it in GitHub Desktop.
flockを孫プロセスに保持させてプロセスの終了までロックを無理やり保持する
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
function flock { | |
typeset unlock_flg=0 | |
while getopts u OPT | |
do | |
case $OPT in | |
u) | |
unlock_flg=1 | |
;; | |
esac | |
done | |
shift $((OPTIND - 1)) | |
typeset lockfile=$1 | |
typeset -i rc | |
if [[ $unlock_flg == 1 ]] | |
then | |
typeset flock_pid=$(ps -eo pid,args | awk -v pid="${$}" -v lockfile="${lockfile}" '$2=="flock" && $3 == pid && $4 == $lockfile{print $1}' | |
if [[ -n "${flock_pid}" ]] | |
then | |
rm -f "${lockfile}" | |
kill -9 "${flock_pid}" | |
return 0 | |
else | |
return 1 | |
fi | |
fi | |
perl -e ' | |
my $lockfile = $ARGV[0]; | |
my $ppid = getppid(); | |
$0 = "flock " . $ppid . " " . $lockfile; | |
$SIG{USR1} = sub { | |
exit(0); | |
}; | |
$SIG{USR2} = sub { | |
exit(1); | |
}; | |
$pid = fork(); | |
if ($pid) { | |
wait(); | |
} else { | |
if (!open(FH, ">>" . $lockfile)) { | |
kill "USR2", getppid(); | |
while (kill(0, getppid())) { | |
sleep(1); | |
} | |
exit(0); | |
} | |
if (!flock(FH, 6)) { | |
kill "USR2", getppid(); | |
while (kill(0, getppid())) { | |
sleep(1); | |
} | |
exit(0); | |
} | |
kill "USR1", getppid(); | |
while (kill(0, $ppid)) { | |
sleep(1); | |
} | |
exit(0); | |
} | |
' ${lockfile}"; rc=$? | |
return "${rc}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment