Use fcntl(2)-style locks instead of less-portable flock(2)-style locks.

Approved by:	re (kensmith)
This commit is contained in:
Dag-Erling Smørgrav 2007-08-03 06:32:45 +00:00
parent fb7557140e
commit 7eb198c642
Notes: svn2git 2020-12-20 02:59:44 +00:00
svn path=/head/; revision=171705
3 changed files with 23 additions and 17 deletions

View File

@ -25,7 +25,7 @@
.\"
.\" $FreeBSD$
.\"
.Dd May 10, 2007
.Dd July 30, 2007
.Dt FLOPEN 3
.Os
.Sh NAME
@ -46,12 +46,9 @@ The
function opens or creates a file and acquires an exclusive lock on it.
It is essentially equivalent with calling
.Fn open
with the same parameters followed by
.Fn flock
with an
.Va operation
argument of
.Dv LOCK_EX ,
with the same parameters and then acquiring a lock on the entire file
using
.Fn fcntl "F_SETLK" ,
except that
.Fn flopen
will attempt to detect and handle races that may occur between opening
@ -86,12 +83,12 @@ returns a valid file descriptor.
Otherwise, it returns -1, and sets
.Va errno
as described in
.Xr flock 2
.Xr fcntl 2
and
.Xr open 2 .
.Sh SEE ALSO
.Xr errno 2 ,
.Xr flock 2 ,
.Xr fcntl 2 ,
.Xr open 2
.Sh AUTHORS
.An -nosplit

View File

@ -43,6 +43,7 @@ flopen(const char *path, int flags, ...)
{
int fd, operation, serrno, trunc;
struct stat sb, fsb;
struct flock lock;
mode_t mode;
#ifdef O_EXLOCK
@ -58,9 +59,11 @@ flopen(const char *path, int flags, ...)
va_end(ap);
}
operation = LOCK_EX;
if (flags & O_NONBLOCK)
operation |= LOCK_NB;
lock.l_type = (flags & O_RDONLY) ? F_RDLCK : F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
operation = (flags & O_NONBLOCK) ? F_SETLK : F_SETLKW;
trunc = (flags & O_TRUNC);
flags &= ~O_TRUNC;
@ -69,7 +72,7 @@ flopen(const char *path, int flags, ...)
if ((fd = open(path, flags, mode)) == -1)
/* non-existent or no access */
return (-1);
if (flock(fd, operation) == -1) {
if (fcntl(fd, operation, &lock) == -1) {
/* unsupported or interrupted */
serrno = errno;
close(fd);

View File

@ -31,13 +31,13 @@ __FBSDID("$FreeBSD$");
#include <sys/file.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <err.h>
#include <errno.h>
#include <libutil.h>
static int _pidfile_remove(struct pidfh *pfh, int freeit);
@ -207,8 +207,14 @@ pidfile_close(struct pidfh *pfh)
static int
_pidfile_remove(struct pidfh *pfh, int freeit)
{
struct flock lock;
int error;
lock.l_type = F_UNLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
error = pidfile_verify(pfh);
if (error != 0) {
errno = error;
@ -217,7 +223,7 @@ _pidfile_remove(struct pidfh *pfh, int freeit)
if (unlink(pfh->pf_path) == -1)
error = errno;
if (flock(pfh->pf_fd, LOCK_UN) == -1) {
if (fcntl(pfh->pf_fd, F_SETLK, &lock) == -1) {
if (error == 0)
error = errno;
}