Preventing opening file twice from different processes

2.3k views Asked by At

After a research I made, I'm still not sure if there are APIs that allows you to open file exclusively, meaning, any other process would not be able to right to the file. Please can someone give me a good reference/guide/note/manual that covers this topic?
Thanks a lot!

Edit: Advisory Locking is good enough.

2

There are 2 answers

0
Jonathan Leffler On

There are three primary systems for file locking between processes:

Some Unix-like systems might not have flock(); they might have lockf() instead, for example, or they might only have fcntl() locking (though most will have both lockf() and fcntl() and many will have flock() too). The current version of POSIX mandates fcntl() locking and lockf() locking for file-level inter-process locking. (POSIX also defines flockfile(), funlockfile() and ftrylockfile() — which are used for controlling locking between threads in an application).

AFAIK, you can implement both lockf() and flock() locking using fcntl() locking.

Note that the locking functions work on file descriptors or file streams. Each program will be able to open the file, but will then apply advisory locking calls to check whether it has exclusive access to the file.

Note that some systems support mandatory file locking (indicated by setting the setgid bit on a file while the corresponding group execute bit is not set — so 2644 mode, for example). However, Mac OS X does not support mandatory locking (10.10 Yosemite tested, but prior versions also have this limitation). POSIX does not require mandatory locking support. It was provided on SVR4 systems.

5
Erbureth On

To prevent file reading from multiple processess, all of them must implement the same locking mechanism.

One way would be using flock mechanism, which is not available everywhere. From flock(2) manpage:

CONFORMING TO
    4.4BSD (the flock() call first appeared in 4.2BSD).
    A version of flock(), possibly implemented in terms of fcntl(2),
    appears on most UNIX systems.

Another way would be using a lockfile -- file alongside the original one indicating the lock is active. C11 specifies a modifier x to mode in fopen, which ensures that the file is always created and not opened if it already exists:

FILE * f = fopen("filename.lock", "wx");
if (!f) {
    // File already exists!
    return 0;
}

// Do stuff
fclose(f);
remove("filename.lock");