add file trylock functions

pull/10/head
yuqing 2016-11-13 12:44:24 +08:00
parent bd9a588840
commit 8b563ce830
3 changed files with 44 additions and 7 deletions

View File

@ -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

View File

@ -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);
}

View File

@ -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