Question

I've got a bash script that runs on OSX.
It needs to manipulate some files on a network-share (AFP share on a Synology NAS).

Unfortunately those files are sometimes still being written when the script runs.

How do I determine if the file is in use or not ?

The normal method is by using "lsof", but that doesn't seem to work on network files if the other user is coming from another client on the LAN.

I could just attempt to rename the file. I suppose that will fail if the file is in use, but that is far from elegant.

Anybody have a better solution ?

Was it helpful?

Solution

This is not a generally solvable problem. The typical solution is to write the file to a temporary location and then move it to the final processing directory (since move within a filesystem is generally atomic). If you cannot control how or where the file is written, then you are left with heuristics, particularly doing things like looking at the file and seeing if it hasn't grown in "awhile," but none of these are particularly good compared to separating the writing from the enqueuing.

OTHER TIPS

Are the other potential accesses being done by arbitrary programs or can it be assumed that it's being done by other instances of your program running on other clients?

If the file is private to your program, then all instances of your program can participate in a cooperative locking scheme. You might use the lockfile command, for example. Be very sure to clean up your lock files even in the face of signals/exceptions. You can use the trap built-in command to help with that. See here for an explanation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top