Linux IPC - 记录上锁

简介

记录上锁是读写锁的一种扩展类型,它可用于有亲缘关系或无亲缘关系的进程间共享某个文件的读与写。

fcntl记录上锁

被锁住的文件通过其描述字访问,执行上锁操作的函数是fcntl。这种类型的锁在内核中维护,其宿主标识为fcntl调用进程的进程ID。这意味着这些锁用于不同进程间的上锁,而不是同一进程内不同线程间的上锁。fcntl记录上锁即可用于读也可用于写,对于文件的任意字节,最多只能存在一种类型的锁(读锁或写锁)。而且,一个给定字节可以有多个读写锁,但只能有一个写入锁。
NAME
       fcntl - manipulate file descriptor
SYNOPSIS
       #include <unistd.h>
       #include <fcntl.h>
       int fcntl(int fd, int cmd, ... /* arg */ );

	   
       Linux  implements traditional ("process-associated") UNIX record locks, as standardized by POSIX.  For a Linux-specific alter‐
       native with better semantics, see the discussion of open file description locks below.

       F_SETLK, F_SETLKW, and F_GETLK are used to acquire, release, and test for the existence of record locks (also known  as  byte-
       range,  file-segment, or file-region locks).  The third argument, lock, is a pointer to a structure that has at least the fol‐
       lowing fields (in unspecified order).

           struct flock {
               ...
               short l_type;    /* Type of lock: F_RDLCK,
                                   F_WRLCK, F_UNLCK */
               short l_whence;  /* How to interpret l_start:
                                   SEEK_SET, SEEK_CUR, SEEK_END */
               off_t l_start;   /* Starting offset for lock */
               off_t l_len;     /* Number of bytes to lock */
               pid_t l_pid;     /* PID of process blocking our lock
                                   (set by F_GETLK and F_OFD_GETLK) */
               ...
           };
锁不能通过fork由子进程继承。对于一个打开着某个文件的给定进程来说,当它关闭该文件的任何一个描述字或者终止时,与该文件关联的所有锁都被删除。这个是非常有用的特性,当程序出现异常时,不需要用户去=清除锁状态。

典型应用

记录上锁的一个常见用途是确保某个程序(例如守护程序)任何时刻只有一个拷贝在运行。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define	PATH_PIDFILE	"pidfile"
#define	MAXLINE		4096	/* max text line length */
#define	FILE_MODE	(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) /* default permissions for new files */

int
lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
	struct flock	lock;

	lock.l_type = type;		/* F_RDLCK, F_WRLCK, F_UNLCK */
	lock.l_start = offset;	/* byte offset, relative to l_whence */
	lock.l_whence = whence;	/* SEEK_SET, SEEK_CUR, SEEK_END */
	lock.l_len = len;		/* #bytes (0 means to EOF) */

	return( fcntl(fd, cmd, &lock) );	/* -1 upon error */
}

#define	write_lock(fd, offset, whence, len) \
			lock_reg(fd, F_SETLK, F_WRLCK, offset, whence, len)

int
main(int argc, char **argv) {
	int		pidfd;
	char	line[MAXLINE];

		/* 4open the PID file, create if nonexistent */
	pidfd = open(PATH_PIDFILE, O_RDWR | O_CREAT, FILE_MODE);
	if (pidfd == -1) {
		printf("Open error for %s", PATH_PIDFILE);

		exit(1);
	}

	/* 4try to write lock the entire file */
	if (write_lock(pidfd, 0, SEEK_SET, 0) < 0) {
		if (errno == EACCES || errno == EAGAIN)
			printf("unable to lock %s, is %s already running?",
					 PATH_PIDFILE, argv[0]);
		else
			printf("unable to lock %s", PATH_PIDFILE);

		exit(1);
	}

	/* 4write my PID, leave file open to hold the write lock */
	snprintf(line, sizeof(line), "%ld\n", (long) getpid());
	if (ftruncate(pidfd, 0) == -1) {
		printf("unable to truncated %s", PATH_PIDFILE);
		exit(1);
	}

	if (write(pidfd, line, strlen(line)) == -1) {
		printf("unable to truncated %s", PATH_PIDFILE);
		exit(1);
	}

	/* then do whatever the daemon does ... */

	pause();
}
执行相应程序可以证实记录锁的特点: 进程退出后锁自动清除。
bob@ubuntu:~$ ./daemon &
[1] 6555
bob@ubuntu:~$ ./daemon &
[2] 6556
unable to lock pidfile, is ./daemon already running?
[2]+  Exit 1                  ./daemon
bob@ubuntu:~$ kill 6555
[1]   Terminated              ./daemon
bob@ubuntu:~$ ./daemon &
[2] 6557
Ubuntu系统中,很多守护进程把各自的进程ID写到一个文件中,并存放在/var/run目录下。
一个守护进程防止自身另外一个拷贝的启动还有其他方法,譬如使用信号量。记录上锁方法的优势在于,许多守护程序都编写某个文件写入本进程ID,而且如果某个守护进程过早崩溃了,那么内核会自动释放它的记录锁。

小结

fcntl记录上锁提供了一个文件的劝告性或强制性上锁功能,而该文件是通过它的打开着的描述符来访问。这些锁用于不同进程间上锁,而不是同一进程内不同线程间上锁。这种类型记录上锁的几乎所有用途都是作为协作进程间的劝告性锁,即使是强制性上锁也会导致不一致的数据。使用fcntl记录上锁时,等待着的读出者优先还是等待着的写入者优先没有保证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值