Dave Wade-Stein
Dave Wade-Stein

Reputation: 275

How to avoid problematic/undefined behavior when locking NFS files on Linux?

I have used flock() and fcntl() in the past, but I've always been concerned that behavior is undefined or problematic for some older versions of Linux.

I need a solution that is compatible with older Linux-es (say, 2.6.18 or better), and NFS 3+.

Will flock() and/or fcntl() work consistently under those circumstances, or do I need to resort to open (.... O_EXCL) to guarantee atomicity?

Upvotes: 3

Views: 339

Answers (2)

John Zwinck
John Zwinck

Reputation: 249293

You definitely cannot expect flock() to work with NFS. fcntl() with F_SETLK has a decent chance of working, with caveats if you have multiple uses in one process: http://0pointer.de/blog/projects/locking.html

Upvotes: 1

David C. Rankin
David C. Rankin

Reputation: 84569

Historically, flock has been available for at least a decade, and implemented by the kernel since 2.0. From the flock man page:

Since kernel 2.0, flock() is implemented as a system call in its own right rather than being emulated in the GNU C library as a call to fcntl(2). This yields true BSD semantics: there is no interaction between the types of lock placed by flock() and fcntl(2), and flock() does not detect deadlock.

I think it will cover your needs, unless you are dealing with pre-2.0 kernels.

Upvotes: 0

Related Questions