struct flock { short l_type; /* F_RDLCK, F_WRLCK, or F_UNLCK */ short l_whence; /* SEEK_SET, SEEK_CUR, SEEK_END */ OFF_T l_start; /* starting offset relative to l_whence */ OFF_T l_len; /* len == 0 means "until end of file" */ pid_t l_pid; /* Process ID of the process holding the lock, returned with F_GETLK */ }; 关于struct flock,锁的范围是这么算的 (l_whence + l_start) ~ (l_whence + l_start + l_len) // 不同的系统,对定义的flock结构,可能不同。
#include <stdio.h> #include <fcntl.h> #include <sys/file.h> #include <stdlib.h> #include <unistd.h> void printLockName(int lockType) { printf("lock type = %d\n", lockType); switch (lockType) { case F_RDLCK : printf("lock type is F_RDLCK\n"); break; case F_WRLCK : printf("lock type is F_WRLCK\n"); break; case F_UNLCK : printf("lock type is F_UNLCK\n"); break; default : printf("not lock type !\n"); } } void setFlock(struct flock *lock, int type, off_t offset, int whence, off_t len) { lock->l_type = type; lock->l_start = offset; lock->l_whence = whence; lock->l_len = len; } int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len) { struct flock lock; setFlock(&lock, type, offset, whence, len); return (fcntl(fd, cmd, &lock)); } pid_t lock_test(int fd, int type, off_t offset, int whence, off_t len) { struct flock lock; setFlock(&lock, type, offset, whence, len); if (fcntl(fd, F_GETLK, &lock) < 0) printf("fcntl error"); printLockName(lock.l_type); if (lock.l_type == F_UNLCK) return 0; return lock.l_pid; } void putexit(char *p) { printf("%s\n", p); exit(1); }
#include <stdio.h> #include <fcntl.h> int main(int argc, char *argv[]) { int fd = open("/home/long/myc/tem.file", O_RDONLY); if (fd < 0) putexit("open file error!"); if (lock_reg(fd, F_SETLK, F_RDLCK, 0, SEEK_SET, 0) == 0) printf("lock_reg OK\n"); printf("getpid() = %d\n", getpid()); sleep(10); close(fd); return 0; }
#include <stdio.h> #include <fcntl.h> int main(int argc, char *argv[]) { int fd = open("/home/long/myc/tem.file", O_WRONLY); if (fd < 0) putexit("open file error!"); int pid = -1; pid = lock_test(fd, F_WRLCK, 0, SEEK_SET, 0); printf("lock pid = %d\n", pid); sleep(10); char buf[] = "hello\0"; if(write(fd, buf, sizeof(buf)) < 0) perror("wrire error"); close(fd); return 0; }