1.进程间同步
(1)
int fcntl(int fd, int cmd, struct flock *);
cmd:
F_SETLCK 非阻塞,获得锁 F_SETLCKW 阻塞,获得锁 F_GETLCK 释放锁
struct flock:
struct flock { ... short l_type; // 锁的类型,F_RDLCK, F_WRLCK, F_UNLCK short l_whence; // 设置锁文件内容的起始位置:SEEK_SET, SEEK_END, SEEK_CUR off_t l_start; // 设置锁文件内容的偏移位置 off_t l_len; // 设置锁文件内容的长度,设置为0表示整个文件 pid_t pid; // 查看阻塞在锁上的进程号,(只用于 F_GETLCK) }
(2)
[1]阻塞方式使用写锁
#include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #define file "./tmp" int main() { int ret = 0; int fd = -1; struct flock flock; if ((fd = open(file, O_RDWR)) < 0) { perror("open"); ret = -1; goto __end__; } flock.l_type = F_WRLCK; flock.l_whence = SEEK_SET; flock.l_start = 0; flock.l_len = 0; fcntl(fd, F_SETLKW, &flock); printf("get lock\n"); sleep(10); flock.l_type = F_UNLCK; printf("unlock\n"); fcntl(fd, F_SETLKW, &flock); __end__: if (fd != -1) close(fd); return ret; }