4 ms·
Can you use something similar for lock files? For instance, I have some script which looks like this: function cleanup() { pkill -P $$ # Kill chi
by mbwgh 3y ago
Can you use something similar for lock files?
For instance, I have some script which looks like this:
function cleanup() {
pkill -P $$ # Kill child processes.
rm -f myscript.lock
}
trap cleanup exit
lockfile -r 0 myscript.lock # Try to create lock file once.
if [[ $? != 0 ]]; then
echo ":("
exit 1
fi
# Work work...
cleanup
Like you said, the cleanup handler is not invoked if the script receives a SIGKILL.
Since the lock file needs to be present in the FS (contrary to a tmp file), maybe this is some inherent limitation, but I would be curious if some better approach exists.
- mplewis9z 3y agoIf you're only trying to coordinate among sub-processes of your top-level script (ones that are at some point forked from the root script and duplicate its file descriptors), there's probably a way to get an approach similar to mine working, though I'd have to think a bit about exactly how to do so. Probably something along the lines of using a FIFO/pipe file in a similar way that I use a normal file in the original snippet. If you're trying to coordinate multiple invocations of the same script, you're out of luck trying to adapt my approach - something has to manage a resource for multiple unrelated processes, and thus they're all going to need a stable identifier of some sort to access it. There might be something mildly better than a filesystem-based lockfile, but it's almost certainly not worth the complexity/unfamiliarity to other people who might use your code. You're probably best off putting a file in a dedicated temporary directory like `/tmp` and relying on out-of-band cleanup to catch things like SIGKILL that will fall through the cracks of your normal cleanup.
- mbwgh 3y agoYeah my use case is unfortunately the latter. Maybe the out-of-band cleanup you suggest might be something like a simple daemon which is invoked with `$$` and `path/to/myscript.lock`. Which would then poll for the presence of a process with the given PID and deletes the lock file.
- lionkor 3y agoI believe the EXIT trap is not clearly defined in POSIX, so you should also trap the other signals you care about (SIGINT, SIGTERM, ...)