From 8b563ce830222507be9d4a4556b0c0ea4389103b Mon Sep 17 00:00:00 2001 From: yuqing Date: Sun, 13 Nov 2016 12:44:24 +0800 Subject: [PATCH] add file trylock functions --- HISTORY | 3 ++- src/shared_func.c | 27 +++++++++++++++++++++------ src/shared_func.h | 21 +++++++++++++++++++++ 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/HISTORY b/HISTORY index 297eb44..ce3b983 100644 --- a/HISTORY +++ b/HISTORY @@ -1,7 +1,8 @@ -Version 1.31 2016-11-11 +Version 1.31 2016-11-13 * move SET_SOCKOPT_NOSIGPIPE from sockopt.c to sockopt.h * add function get_time_item_from_str + * add file trylock functions Version 1.30 2016-10-31 * modify php-fastcommon/test.php diff --git a/src/shared_func.c b/src/shared_func.c index 3c9af55..319031d 100644 --- a/src/shared_func.c +++ b/src/shared_func.c @@ -2319,17 +2319,17 @@ bool is_power2(const int64_t n) return i == n; } -static inline int do_lock_file(int fd, int cmd) +static inline int do_lock_file(int fd, int cmd, int type) { struct flock lock; int result; memset(&lock, 0, sizeof(lock)); - lock.l_type = cmd; + lock.l_type = type; lock.l_whence = SEEK_SET; do { - if ((result=fcntl(fd, F_SETLKW, &lock)) != 0) + if ((result=fcntl(fd, cmd, &lock)) != 0) { result = errno != 0 ? errno : ENOMEM; fprintf(stderr, "call fcntl fail, " @@ -2343,16 +2343,31 @@ static inline int do_lock_file(int fd, int cmd) int file_read_lock(int fd) { - return do_lock_file(fd, F_RDLCK); + return do_lock_file(fd, F_SETLKW, F_RDLCK); } int file_write_lock(int fd) { - return do_lock_file(fd, F_WRLCK); + return do_lock_file(fd, F_SETLKW, F_WRLCK); } int file_unlock(int fd) { - return do_lock_file(fd, F_UNLCK); + return do_lock_file(fd, F_SETLKW, F_UNLCK); +} + +int file_try_read_lock(int fd) +{ + return do_lock_file(fd, F_SETLK, F_RDLCK); +} + +int file_try_write_lock(int fd) +{ + return do_lock_file(fd, F_SETLK, F_WRLCK); +} + +int file_try_unlock(int fd) +{ + return do_lock_file(fd, F_SETLK, F_UNLCK); } diff --git a/src/shared_func.h b/src/shared_func.h index a8a2583..4686f9d 100644 --- a/src/shared_func.h +++ b/src/shared_func.h @@ -587,6 +587,27 @@ int file_write_lock(int fd); */ int file_unlock(int fd); +/** try file read lock + * parameters: + * fd: the file descriptor to lock + * return: error no, 0 for success, != 0 fail +*/ +int file_try_read_lock(int fd); + +/** try file write lock + * parameters: + * fd: the file descriptor to lock + * return: error no, 0 for success, != 0 fail +*/ +int file_try_write_lock(int fd); + +/** try file unlock + * parameters: + * fd: the file descriptor to unlock + * return: error no, 0 for success, != 0 fail +*/ +int file_try_unlock(int fd); + #ifdef __cplusplus } #endif