From 26dacf079558f68480675263b6f9b628b7e7bbdd Mon Sep 17 00:00:00 2001 From: SATOH Fumiyasu Date: Thu, 26 Jun 2008 10:42:46 +0200 Subject: [PATCH] Portability: File locking by fcntl, lockf or flock MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Marcela Mašláňová --- configure.ac | 6 ++++++ src/misc.c | 32 +++++++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index f07e569..a33d8a8 100644 --- a/configure.ac +++ b/configure.ac @@ -41,6 +41,12 @@ AC_CHECK_HEADERS( \ utime.h \ ) +AC_CHECK_FUNCS( \ + fcntl \ + lockf \ + flock \ +) + dnl Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_SIGNAL diff --git a/src/misc.c b/src/misc.c index cfe7aa2..24917ac 100644 --- a/src/misc.c +++ b/src/misc.c @@ -28,6 +28,17 @@ #include #endif +#ifdef HAVE_FCNTL_H /* fcntl(2) */ +# include +#endif +#ifdef HAVE_UNISTD_H /* lockf(3) */ +# include +#endif +#ifdef HAVE_FLOCK /* flock(2) */ +# include +#endif +#include + #if defined(SYSLOG) && defined(LOG_FILE) # undef LOG_FILE #endif @@ -46,6 +57,25 @@ static int LogFD = ERR; static int syslog_open = FALSE; #endif +#if defined(HAVE_FCNTL) && defined(F_SETLK) +static int trylock_file(int fd) +{ + struct flock fl; + + memset(&fl, '\0', sizeof(fl)); + fl.l_type = F_WRLCK; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + + return fcntl(fd, F_SETLK, &fl); +} +#elif defined(HAVE_LOCKF) +# define trylock_file(fd) lockf((fd), F_TLOCK, 0) +#elif defined(HAVE_FLOCK) +# define trylock_file(fd) flock((fd), LOCK_EX|LOCK_NB) +#endif + /* * glue_strings is the overflow-safe equivalent of * sprintf(buffer, "%s%c%s", a, separator, b); @@ -305,7 +335,7 @@ acquire_daemonlock(int closeflag) { exit(ERROR_EXIT); } - if (flock(fd, LOCK_EX|LOCK_NB) < OK) { + if (trylock_file(fd) < OK) { int save_errno = errno; bzero(buf, sizeof(buf)); -- 2.40.0