Created
September 24, 2014 05:18
-
-
Save maliubiao/e9c30540754cb0a7552f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fcntl.h> | |
#include <sys/types.h> | |
#include <time.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <signal.h> | |
char *lock_path = NULL; | |
int try_lock(const char *path) | |
{ | |
int fd; | |
int status; | |
struct flock f; | |
f.l_type = F_WRLCK; | |
f.l_whence = SEEK_SET; | |
f.l_start = 0; | |
f.l_len = 10; | |
fd = open(path, O_RDWR); | |
if (fd < 0) { | |
printf("open %s failed\n", path); | |
return fd; | |
} | |
status = fcntl(fd, F_GETLK, &f); | |
if (status < 0) { | |
printf("fcntl failed\n"); | |
return status; | |
} | |
if (f.l_type != F_UNLCK) { | |
printf("pid %d is holding the lock\n", f.l_pid); | |
return status; | |
} | |
printf("access ok\n"); | |
return 0; | |
} | |
int acquire_hold_lock(const char *path) | |
{ | |
int fd; | |
int status; | |
struct flock f; | |
f.l_type = F_WRLCK; | |
f.l_whence = SEEK_SET; | |
f.l_start = 0; | |
f.l_len = 10; | |
fd = open(path, O_CREAT|O_TRUNC|O_RDWR, S_IWUSR|S_IRUSR); | |
if (fd < 0) { | |
printf("create %s failed\n", path); | |
return -1; | |
} | |
status = fcntl(fd, F_SETLK, &f); | |
if (status < 0) { | |
printf("lock failed\n"); | |
return -1; | |
} | |
printf("lock file %s\n", path); | |
printf("my pid: %d\n", getpid()); | |
while(1) { | |
sleep(1); | |
} | |
return 0; | |
} | |
int flock_strcmp(const char *s1, const char *s2) | |
{ | |
while(*s1 == *s2 && *s1 != '\0') { | |
s1 ++; | |
s2 ++; | |
} | |
return (unsigned char)*s1 - (unsigned char)*s2; | |
} | |
int flock_strlen(const char *s) | |
{ | |
const char *s1 = s; | |
while(*s1 != '\0') { | |
s ++; | |
} | |
return s1 - s; | |
} | |
void print_usage(void) | |
{ | |
printf("-l lock name, create a lock and keep it, press CTRL-C to quit\n" | |
"-t lock name, access the lock file\n"); | |
} | |
void sigint_handler(int signum) | |
{ | |
int status; | |
status = unlink(lock_path); | |
if (status < 0) { | |
printf("unlink failed\n"); | |
} | |
exit(0); | |
} | |
int main(int argc, char **argv) | |
{ | |
if (argc < 3) { | |
print_usage(); | |
exit(0); | |
} | |
if (flock_strcmp(argv[1], "-l") == 0) { | |
lock_path = argv[2]; | |
signal(SIGINT, sigint_handler); | |
acquire_hold_lock(argv[2]); | |
} else if (flock_strcmp(argv[1], "-t") == 0) { | |
try_lock(argv[2]); | |
} else { | |
print_usage(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment