File Locks (The GNU C Library) (2024)

Next: Open File Description Locks, Previous: File Status Flags, Up: Low-Level Input/Output [Contents][Index]

13.16 File Locks

This section describes record locks that are associated with the process.There is also a different type of record lock that is associated with theopen file description instead of the process. See Open File Description Locks.

The remaining fcntl commands are used to support recordlocking, which permits multiple cooperating programs to prevent eachother from simultaneously accessing parts of a file in error-proneways.

An exclusive or write lock gives a process exclusive accessfor writing to the specified part of the file. While a write lock is inplace, no other process can lock that part of the file.

A shared or read lock prohibits any other process fromrequesting a write lock on the specified part of the file. However,other processes can request read locks.

The read and write functions do not actually check to seewhether there are any locks in place. If you want to implement alocking protocol for a file shared by multiple processes, your applicationmust do explicit fcntl calls to request and clear locks at theappropriate points.

Locks are associated with processes. A process can only have one kindof lock set for each byte of a given file. When any file descriptor forthat file is closed by the process, all of the locks that process holdson that file are released, even if the locks were made using otherdescriptors that remain open. Likewise, locks are released when aprocess exits, and are not inherited by child processes created usingfork (see Creating a Process).

When making a lock, use a struct flock to specify what kind oflock and where. This data type and the associated macros for thefcntl function are declared in the header file fcntl.h.

Data Type: struct flock

This structure is used with the fcntl function to describe a filelock. It has these members:

short int l_type

Specifies the type of the lock; one of F_RDLCK, F_WRLCK, orF_UNLCK.

short int l_whence

This corresponds to the whence argument to fseek orlseek, and specifies what the offset is relative to. Its valuecan be one of SEEK_SET, SEEK_CUR, or SEEK_END.

off_t l_start

This specifies the offset of the start of the region to which the lockapplies, and is given in bytes relative to the point specified by thel_whence member.

off_t l_len

This specifies the length of the region to be locked. A value of0 is treated specially; it means the region extends to the end ofthe file.

pid_t l_pid

This field is the process ID (see Process Creation Concepts) of theprocess holding the lock. It is filled in by calling fcntl withthe F_GETLK command, but is ignored when making a lock. If theconflicting lock is an open file description lock(see Open File Description Locks), then this field will be set to-1.

Macro: int F_GETLK

This macro is used as the command argument to fcntl, tospecify that it should get information about a lock. This commandrequires a third argument of type structflock* to be passedto fcntl, so that the form of the call is:

fcntl (filedes, F_GETLK, lockp)

If there is a lock already in place that would block the lock describedby the lockp argument, information about that lock overwrites*lockp. Existing locks are not reported if they arecompatible with making a new lock as specified. Thus, you shouldspecify a lock type of F_WRLCK if you want to find out about bothread and write locks, or F_RDLCK if you want to find out aboutwrite locks only.

There might be more than one lock affecting the region specified by thelockp argument, but fcntl only returns information aboutone of them. The l_whence member of the lockp structure isset to SEEK_SET and the l_start and l_len fieldsset to identify the locked region.

If no lock applies, the only change to the lockp structure is toupdate the l_type to a value of F_UNLCK.

The normal return value from fcntl with this command is anunspecified value other than -1, which is reserved to indicate anerror. The following errno error conditions are defined forthis command:

EBADF

The filedes argument is invalid.

EINVAL

Either the lockp argument doesn’t specify valid lock information,or the file associated with filedes doesn’t support locks.

Macro: int F_SETLK

This macro is used as the command argument to fcntl, tospecify that it should set or clear a lock. This command requires athird argument of type structflock* to be passed tofcntl, so that the form of the call is:

fcntl (filedes, F_SETLK, lockp)

If the process already has a lock on any part of the region, the old lockon that part is replaced with the new lock. You can remove a lockby specifying a lock type of F_UNLCK.

If the lock cannot be set, fcntl returns immediately with a valueof -1. This function does not block while waiting for other processesto release locks. If fcntl succeeds, it returns a value otherthan -1.

The following errno error conditions are defined for thisfunction:

EAGAIN
EACCES

The lock cannot be set because it is blocked by an existing lock on thefile. Some systems use EAGAIN in this case, and other systemsuse EACCES; your program should treat them alike, afterF_SETLK. (GNU/Linux and GNU/Hurd systems always use EAGAIN.)

EBADF

Either: the filedes argument is invalid; you requested a read lockbut the filedes is not open for read access; or, you requested awrite lock but the filedes is not open for write access.

EINVAL

Either the lockp argument doesn’t specify valid lock information,or the file associated with filedes doesn’t support locks.

ENOLCK

The system has run out of file lock resources; there are already toomany file locks in place.

Well-designed file systems never report this error, because they have nolimitation on the number of locks. However, you must still take accountof the possibility of this error, as it could result from network accessto a file system on another machine.

Macro: int F_SETLKW

This macro is used as the command argument to fcntl, tospecify that it should set or clear a lock. It is just like theF_SETLK command, but causes the process to block (or wait)until the request can be specified.

This command requires a third argument of type struct flock *, asfor the F_SETLK command.

The fcntl return values and errors are the same as for theF_SETLK command, but these additional errno error conditionsare defined for this command:

EINTR

The function was interrupted by a signal while it was waiting.See Primitives Interrupted by Signals.

EDEADLK

The specified region is being locked by another process. But thatprocess is waiting to lock a region which the current process haslocked, so waiting for the lock would result in deadlock. The systemdoes not guarantee that it will detect all such conditions, but it letsyou know if it notices one.

The following macros are defined for use as values for the l_typemember of the flock structure. The values are integer constants.

F_RDLCK

This macro is used to specify a read (or shared) lock.

F_WRLCK

This macro is used to specify a write (or exclusive) lock.

F_UNLCK

This macro is used to specify that the region is unlocked.

As an example of a situation where file locking is useful, consider aprogram that can be run simultaneously by several different users, thatlogs status information to a common file. One example of such a programmight be a game that uses a file to keep track of high scores. Anotherexample might be a program that records usage or accounting informationfor billing purposes.

Having multiple copies of the program simultaneously writing to thefile could cause the contents of the file to become mixed up. Butyou can prevent this kind of problem by setting a write lock on thefile before actually writing to the file.

If the program also needs to read the file and wants to make sure thatthe contents of the file are in a consistent state, then it can also usea read lock. While the read lock is set, no other process can lockthat part of the file for writing.

Remember that file locks are only an advisory protocol forcontrolling access to a file. There is still potential for access tothe file by programs that don’t use the lock protocol.

File Locks (The GNU C Library) (2024)

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Pres. Lawanda Wiegand

Last Updated:

Views: 6716

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Pres. Lawanda Wiegand

Birthday: 1993-01-10

Address: Suite 391 6963 Ullrich Shore, Bellefort, WI 01350-7893

Phone: +6806610432415

Job: Dynamic Manufacturing Assistant

Hobby: amateur radio, Taekwondo, Wood carving, Parkour, Skateboarding, Running, Rafting

Introduction: My name is Pres. Lawanda Wiegand, I am a inquisitive, helpful, glamorous, cheerful, open, clever, innocent person who loves writing and wants to share my knowledge and understanding with you.