Detect file in use by other process

£可爱£侵袭症+ 提交于 2019-11-30 19:55:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!