Originally Posted by edenCC
One of my friends gave me another solution
It's not as good as your solution because of the race condition between
fuser "$f" &> /dev/null
eval "exec $freefd< \"$f\""
Another instance of the script could use fuser, find no lock and also open the lock file.
Co-operative locking between asynchronous processes requires an atomic operation, that is an operation which is guaranteed not to be interrupted between initiation and completion. AFAIK there are only two such filesystem-related primitives: ln and mkdir.
The existence of procmail's "lockfile" command saves shellscript coders a lot of work in this area! It includes a -l timeout function to set the maximum age of a lockfile -- useful if you can be sure of the maximum time the lock must be held for.
For debugging and sysadmin it is helpful if the process that created a log file writes its ID info into the lockfile. I don't think procmail's lockfile supports that.