Hi,
I'm trying to lock a file from objective-c (or plain C) so that other processes cannot read or write to it. So far, unsuccessfully.
I've tried to use all APIs I can think of, but none locked the file:
open
thenflock
open
thenlockf
open
withO_EXLOCK
open
thenfcntl
(F_SETLK
)open
thenNSDistributedLock
I'm running macOS 11.6.1 on an APFS drive.
For every API used, I was able to open and edit the file from command line using vi
or just using cat
on the file.
Isn't there any way of preventing another process from accessing a file, until I'm done with it (ie. I closed the file, or the file handle is relinquished)?
Thanks, Chris
What you're asking for is called "mandatory locking".
What those functions provide is "advisory locking". Advisory locking depends on all users of the file using the locking functions.
Historically, Windows has provided mandatory locking; POSIX (Unix) has provided mostly advisory locking. I believe that Mac OS, and iOS, follow POSIX here.
So no, I do not believe that you will find a way to lock a file so that another (uncooperative) process will be unable to access it.
Some work-around:
- Modify the permissions of the file while you modify it.
- Make a temporary copy of the file, and rename() it over the original (which is atomic) when you have finished.
(What do you really want to achieve?)