Skip to content

Commit

Permalink
Add functions for operating with file locks
Browse files Browse the repository at this point in the history
Signed-off-by: Alexey Gladkov <legion@altlinux.org>
  • Loading branch information
legionus committed Feb 7, 2024
1 parent fd7c4b9 commit 6e89a9f
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
42 changes: 42 additions & 0 deletions docs/shell-locks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
shell-locks(3)

# NAME

fd_rlock, fd_lock, fd_trylock, fd_unlock, fd_is_locked - Functions for operating
with file locks.

# SYNOPSIS

- fd_rlock $num $filename
- fd_lock $num $filename
- fd_trylock $num $filename
- fd_unlock $fd_num
- fd_is_locked $filename

# DESCRIPTION

## fd_rlock
The function opens the file to the specified descriptor and takes a read lock.

## fd_lock
The function opens the file to the specified descriptor and takes a write lock.

## fd_trylock
The function opens the file to the specified descriptor and takes a write lock.
If the lock could not be taken, then the function failed.

## fd_unlock
Closes the descriptor and releases the lock.

## fd_is_locked
Checks whether a lock is present on the specified file.

# ENVIRONMENT

# AUTHOR
Authors and contributors of the programs included in the *libshell* package are listed
in the COPYING file.

# BUGS
Report bugs to the authors.

52 changes: 52 additions & 0 deletions shell-locks
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/bin/bash -efu
# SPDX-License-Identifier: GPL-2.0-or-later

if [ -z "${__included_shell_locks-}" ]; then
__included_shell_locks=1

__shell_fd_lock()
{
local fd="$1"; shift
local fn="$1"; shift
eval "exec $fd<\"$fn\""
flock "$@" "$fd"
}

### The function opens the file to the specified descriptor and takes a read
### lock.
### Usage: fd_rlock $num $filename
fd_rlock() { __shell_fd_lock "$1" "$2" -s; }

### The function opens the file to the specified descriptor and takes a write
### lock.
### Usage: fd_lock $num $filename
fd_lock() { __shell_fd_lock "$1" "$2" -x; }

### The function opens the file to the specified descriptor and takes a write
### lock. If the lock could not be taken, then the function failed.
### Usage: fd_trylock $num $filename
fd_trylock() { __shell_fd_lock "$1" "$2" -n; }

### Closes the descriptor and releases the lock.
### Usage: fd_unlock $fd_num
fd_unlock() { eval "exec $1<&-"; }

### Checks whether a lock is present on the specified file.
### Usage: fd_is_locked $filename
fd_is_locked()
{
local fd=0
while [ -e "/proc/self/fd/$fd" ]; do
fd=$(( $fd + 1 ))
done

if fd_trylock "$fd" "$1"; then
fd_unlock "$fd"
return 1
fi

eval "exec $fd<&-"
return 0
}

fi #__included_shell_locks

0 comments on commit 6e89a9f

Please sign in to comment.