问题
On windows and such I used to use a trick to find out of a file is currently in use (written specifically).
I use to open the file for writing and if it failed most likey another process is busy accessing it.
Sadly these trick (using C OPEN with exclusive lock for writing) doesn't work on my Mac. While my curl in a terminal is still writing my -fileBusy() check fails.
fcnt call on the fd with F_GETLK doesn't reveal any locking as well.
Is there any chance for me to detect if a file is in use by another process?
Ps> listening for fsevents can't be done because my app launches after the is created by the other app / process.
回答1:
Apple confirmed via email that the solution described in the link below is a valid one and not considered a private API.
More information: http://lists.apple.com/archives/cocoa-dev/2010/May/msg01455.html
回答2:
You could try running the following shell command using NSTask:lsof -Fc path/to/thefile
That will give you the process ID and name of any process(es) that have thefile open.
来源:https://stackoverflow.com/questions/8645831/detect-file-in-use-by-other-process