Linux fcntl blocking mode

File locking in Linux

Table of contents

Introduction

File locking is a mutual-exclusion mechanism for files. Linux supports two major kinds of file locks:

  • advisory locks
  • mandatory locks

Below we discuss all lock types available in POSIX and Linux and provide usage examples.

Advisory locking

Traditionally, locks are advisory in Unix. They work only when a process explicitly acquires and releases locks, and are ignored if a process is not aware of locks.

There are several types of advisory locks available in Linux:

  • BSD locks (flock)
  • POSIX record locks (fcntl, lockf)
  • Open file description locks (fcntl)

All locks except the lockf function are reader-writer locks, i.e. support exclusive and shared modes.

Note that flockfile and friends have nothing to do with the file locks. They manage internal mutex of the FILE object from stdio.

  • File Locks, GNU libc manual
  • Open File Description Locks, GNU libc manual
  • File-private POSIX locks, an LWN article about the predecessor of open file description locks

Common features

The following features are common for locks of all types:

  • All locks support blocking and non-blocking operations.
  • Locks are allowed only on files, but not directories.
  • Locks are automatically removed when the process exits or terminates. It’s guaranteed that if a lock is acquired, the process acquiring the lock is still alive.

Differing features

This table summarizes the difference between the lock types. A more detailed description and usage examples are provided below.

BSD locks lockf function POSIX record locks Open file description locks
Portability widely available POSIX (XSI) POSIX (base standard) Linux 3.15+
Associated with File object [i-node, pid] pair [i-node, pid] pair File object
Applying to byte range no yes yes yes
Support exclusive and shared modes yes no yes yes
Atomic mode switch no yes yes
Works on NFS (Linux) Linux 2.6.12+ yes yes yes

File descriptors and i-nodes

A file descriptor is an index in the per-process file descriptor table (in the left of the picture). Each file descriptor table entry contains a reference to a file object, stored in the file table (in the middle of the picture). Each file object contains a reference to an i-node, stored in the i-node table (in the right of the picture).

A file descriptor is just a number that is used to refer a file object from the user space. A file object represents an opened file. It contains things likes current read/write offset, non-blocking flag and another non-persistent state. An i-node represents a filesystem object. It contains things like file meta-information (e.g. owner and permissions) and references to data blocks.

File descriptors created by several open() calls for the same file path point to different file objects, but these file objects point to the same i-node. Duplicated file descriptors created by dup2() or fork() point to the same file object.

A BSD lock and an Open file description lock is associated with a file object, while a POSIX record lock is associated with an [i-node, pid] pair. We’ll discuss it below.

BSD locks (flock)

The simplest and most common file locks are provided by flock(2) .

  • not specified in POSIX, but widely available on various Unix systems
  • always lock the entire file
  • associated with a file object
  • do not guarantee atomic switch between the locking modes (exclusive and shared)
  • up to Linux 2.6.11, didn’t work on NFS; since Linux 2.6.12, flock() locks on NFS are emulated using fcntl() POSIX record byte-range locks on the entire file (unless the emulation is disabled in the NFS mount options)

The lock acquisition is associated with a file object, i.e.:

  • duplicated file descriptors, e.g. created using dup2 or fork , share the lock acquisition;
  • independent file descriptors, e.g. created using two open calls (even for the same file), don’t share the lock acquisition;

This means that with BSD locks, threads or processes can’t be synchronized on the same or duplicated file descriptor, but nevertheless, both can be synchronized on independent file descriptors.

Читайте также:  Arch linux and nvidia

flock() doesn’t guarantee atomic mode switch. From the man page:

Converting a lock (shared to exclusive, or vice versa) is not guaranteed to be atomic: the existing lock is first removed, and then a new lock is established. Between these two steps, a pending lock request by another process may be granted, with the result that the conversion either blocks, or fails if LOCK_NB was specified. (This is the original BSD behaviour, and occurs on many other implementations.)

This problem is solved by POSIX record locks and Open file description locks.

POSIX record locks (fcntl)

POSIX record locks, also known as process-associated locks, are provided by fcntl(2) , see “Advisory record locking” section in the man page.

  • specified in POSIX (base standard)
  • can be applied to a byte range
  • associated with an [i-node, pid] pair instead of a file object
  • guarantee atomic switch between the locking modes (exclusive and shared)
  • work on NFS (on Linux)

The lock acquisition is associated with an [i-node, pid] pair, i.e.:

  • file descriptors opened by the same process for the same file share the lock acquisition (even independent file descriptors, e.g. created using two open calls);
  • file descriptors opened by different processes don’t share the lock acquisition;

This means that with POSIX record locks, it is possible to synchronize processes, but not threads. All threads belonging to the same process always share the lock acquisition of a file, which means that:

  • the lock acquired through some file descriptor by some thread may be released through another file descriptor by another thread;
  • when any thread calls close on any descriptor referring to given file, the lock is released for the whole process, even if there are other opened descriptors referring to this file.

This problem is solved by Open file description locks.

lockf function

lockf(3) function is a simplified version of POSIX record locks.

  • specified in POSIX (XSI)
  • can be applied to a byte range (optionally automatically expanding when data is appended in future)
  • associated with an [i-node, pid] pair instead of a file object
  • supports only exclusive locks
  • works on NFS (on Linux)

Since lockf locks are associated with an [i-node, pid] pair, they have the same problems as POSIX record locks described above.

The interaction between lockf and other types of locks is not specified by POSIX. On Linux, lockf is just a wrapper for POSIX record locks.

Open file description locks (fcntl)

Open file description locks are Linux-specific and combine advantages of the BSD locks and POSIX record locks. They are provided by fcntl(2) , see “Open file description locks (non-POSIX)” section in the man page.

  • Linux-specific, not specified in POSIX
  • can be applied to a byte range
  • associated with a file object
  • guarantee atomic switch between the locking modes (exclusive and shared)
  • work on NFS (on Linux)

Thus, Open file description locks combine advantages of BSD locks and POSIX record locks: they provide both atomic switch between the locking modes, and the ability to synchronize both threads and processes.

These locks are available since the 3.15 kernel.

The API is the same as for POSIX record locks (see above). It uses struct flock too. The only difference is in fcntl command names:

  • F_OFD_SETLK instead of F_SETLK
  • F_OFD_SETLKW instead of F_SETLKW
  • F_OFD_GETLK instead of F_GETLK

Emulating Open file description locks

What do we have for multithreading and atomicity so far?

  • BSD locks allow thread synchronization but don’t allow atomic mode switch.
  • POSIX record locks don’t allow thread synchronization but allow atomic mode switch.
  • Open file description locks allow both but are available only on recent Linux kernels.

If you need both features but can’t use Open file description locks (e.g. you’re using some embedded system with an outdated Linux kernel), you can emulate them on top of the POSIX record locks.

Here is one possible approach:

Implement your own API for file locks. Ensure that all threads always use this API instead of using fcntl() directly. Ensure that threads never open and close lock-files directly.

In the API, implement a process-wide singleton (shared by all threads) holding all currently acquired locks.

Associate two additional objects with every acquired lock:

Читайте также:  При обновлении windows ошибка 80070000e

Now, you can implement lock operations as follows:

  • First, acquire the RW-mutex. If the user requested the shared mode, acquire a read lock. If the user requested the exclusive mode, acquire a write lock.
  • Check the counter. If it’s zero, also acquire the file lock using fcntl() .
  • Increment the counter.
  • Decrement the counter.
  • If the counter becomes zero, release the file lock using fcntl() .
  • Release the RW-mutex.

This approach makes possible both thread and process synchronization.

Test program

I’ve prepared a small program that helps to learn the behavior of different lock types.

The program starts two threads or processes, both of which wait to acquire the lock, then sleep for one second, and then release the lock. It has three parameters:

lock mode: flock (BSD locks), lockf , fcntl_posix (POSIX record locks), fcntl_linux (Open file description locks)

access mode: same_fd (access lock via the same descriptor), dup_fd (access lock via duplicated descriptors), two_fds (access lock via two descriptors opened independently for the same path)

concurrency mode: threads (access lock from two threads), processes (access lock from two processes)

Below you can find some examples.

Threads are not serialized if they use BSD locks on duplicated descriptors:

But they are serialized if they are used on two independent descriptors:

Threads are not serialized if they use POSIX record locks on two independent descriptors:

But processes are serialized:

Command-line tools

The following tools may be used to acquire and release file locks from the command line:

Provided by util-linux package. Uses flock() function.

There are two ways to use this tool:

run a command while holding a lock:

flock will acquire the lock, run the command, and release the lock.

open a file descriptor in bash and use flock to acquire and release the lock manually:

You can try to run these two snippets in parallel in different terminals and see that while one is sleeping while holding the lock, another is blocked in flock.

Provided by procmail package.

Runs the given command while holding a lock. Can use either flock() , lockf() , or fcntl() function, depending on what’s available on the system.

There are also two ways to inspect the currently acquired locks:

Provided by util-linux package.

Lists all the currently held file locks in the entire system. Allows to perform filtering by PID and to configure the output format.

A file in procfs virtual file system that shows current file locks of all types. The lslocks tools relies on this file.

Mandatory locking

Linux has limited support for mandatory file locking. See the “Mandatory locking” section in the fcntl(2) man page.

A mandatory lock is activated for a file when all of these conditions are met:

  • The partition was mounted with the mand option.
  • The set-group-ID bit is on and group-execute bit is off for the file.
  • A POSIX record lock is acquired.

Note that the set-group-ID bit has its regular meaning of elevating privileges when the group-execute bit is on and a special meaning of enabling mandatory locking when the group-execute bit is off.

When a mandatory lock is activated, it affects regular system calls on the file:

When an exclusive or shared lock is acquired, all system calls that modify the file (e.g. open() and truncate() ) are blocked until the lock is released.

When an exclusive lock is acquired, all system calls that read from the file (e.g. read() ) are blocked until the lock is released.

However, the documentation mentions that current implementation is not reliable, in particular:

  • races are possible when locks are acquired concurrently with read() or write()
  • races are possible when using mmap()

Since mandatory locks are not allowed for directories and are ignored by unlink() and rename() calls, you can’t prevent file deletion or renaming using these locks.

Example usage

Below you can find a usage example of mandatory locking.

Mount the partition and create a file with the mandatory locking enabled:

Acquire a lock in the first terminal:

Try to read the file in the second terminal:

Источник

6.5. Blocking vs. non-blocking sockets

So far in this chapter, you’ve seen that select() can be used to detect when data is available to read from a socket. However, there are times when its useful to be able to call send(), recv(), connect(), accept(), etc without having to wait for the result.

Читайте также:  Kali linux nethunter как пользоваться

For example, let’s say that you’re writing a web browser. You try to connect to a web server, but the server isn’t responding. When a user presses (or clicks) a stop button, you want the connect() API to stop trying to connect.

With what you’ve learned so far, that can’t be done. When you issue a call to connect(), your program doesn’t regain control until either the connection is made, or an error occurs.

The solution to this problem is called «non-blocking sockets».

By default, TCP sockets are in «blocking» mode. For example, when you call recv() to read from a stream, control isn’t returned to your program until at least one byte of data is read from the remote site. This process of waiting for data to appear is referred to as «blocking». The same is true for the write() API, the connect() API, etc. When you run them, the connection «blocks» until the operation is complete.

Its possible to set a descriptor so that it is placed in «non-blocking» mode. When placed in non-blocking mode, you never wait for an operation to complete. This is an invaluable tool if you need to switch between many different connected sockets, and want to ensure that none of them cause the program to «lock up.»

If you call «recv()» in non-blocking mode, it will return any data that the system has in it’s read buffer for that socket. But, it won’t wait for that data. If the read buffer is empty, the system will return from recv() immediately saying « «Operation Would Block!»».

The same is true of the send() API. When you call send(), it puts the data into a buffer, and as it’s read by the remote site, it’s removed from the buffer. If the buffer ever gets «full», the system will return the error ‘Operation Would Block» the next time you try to write to it.

Non-blocking sockets have a similar effect on the accept() API. When you call accept(), and there isn’t already a client connecting to you, it will return ‘Operation Would Block’, to tell you that it can’t complete the accept() without waiting.

The connect() API is a little different. If you try to call connect() in non-blocking mode, and the API can’t connect instantly, it will return the error code for ‘Operation In Progress’. When you call connect() again, later, it may tell you ‘Operation Already In Progress’ to let you know that it’s still trying to connect, or it may give you a successful return code, telling you that the connect has been made.

Going back to the «web browser» example, if you put the socket that was connecting to the web server into non-blocking mode, you could then call connect(), print a message saying «connecting to host www.floofy.com. » then maybe do something else, and them come back to connect() again. If connect() works the second time, you might print «Host contacted, waiting for reply. » and then start calling send() and recv(). If the connect() is still pending, you might check to see if the user has pressed a «abort» button, and if so, call close() to stop trying to connect.

Non-blocking sockets can also be used in conjunction with the select() API. In fact, if you reach a point where you actually WANT to wait for data on a socket that was previously marked as «non-blocking», you could simulate a blocking recv() just by calling select() first, followed by recv().

The «non-blocking» mode is set by changing one of the socket’s «flags». The flags are a series of bits, each one representing a different capability of the socket. So, to turn on non-blocking mode requires three steps:

Call the fcntl() API to retrieve the socket descriptor’s current flag settings into a local variable.

In our local variable, set the O_NONBLOCK (non-blocking) flag on. (being careful, of course, not to tamper with the other flags)

Call the fcntl() API to set the flags for the descriptor to the value in our local variable.

Источник

Оцените статью