3

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.

Ger Teunis
  • 945
  • 1
  • 14
  • 30

2 Answers2

5

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

jtbandes
  • 115,675
  • 35
  • 233
  • 266
Ger Teunis
  • 945
  • 1
  • 14
  • 30
  • Apple aren't redirecting HTTP to HTTPS, so the link in the answer is now - https://lists.apple.com/archives/cocoa-dev/2010/May/msg01455.html A blast from the past to see an Apple domain URL without SSL activated. – Chris Feb 23 '21 at 18:39
1

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.

Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
  • Good suggestion. There is no c API for lsof available? Kicking off tasks will work but for some reason gives me the shivers. – Ger Teunis Dec 27 '11 at 20:05
  • I don't know of any C POSIX API function to accomplish the same thing. I agree that kicking off NSTasks is not usually my favorite way to do things, but so far I don't know of an alternative in this case. I'd love to find out about one! – Andrew Madsen Dec 27 '11 at 22:44
  • 1
    I found more info with a solution which might use a private API : http://web.archiveorange.com/archive/v/SEb6ahosyxznFKzz63G1 I'm still searching for a better solution. – Ger Teunis Dec 28 '11 at 09:02
  • lsof does not work in sandbox... so I'm interested in that other method... but the links leads to Shakespeare ^^ – Axel Zehden Jun 30 '15 at 09:01