当前位置: 首页 > 工具软件 > Flock > 使用案例 >

struct flock 结构体详解及用法

戎元忠
2023-12-01

//该部分内容摘抄至网络

功能 :定义一些文件的锁的选项

Description

The flock structure in the /usr/include/sys/flock.h file, which describes a lock, contains the following fields:

 

l_type Describes the type of lock. If the value of the Command parameter to the fcntl subroutine is F_SETLK orF_SETLKW, the l_type field indicates the type of lock to be created. Possible values are:
F_RDLCK
A read lock is requested.
F_WRLCK
A write lock is requested.
F_UNLCK
Unlock. An existing lock is to be removed.

If the value of the Command parameter to the fcntl subroutine is F_GETLK, the l_typefield describes an existing lock. Possible values are:

F_RDLCK
A conflicting read lock exists.
F_WRLCK
A conflicting write lock exists.
F_UNLCK
No conflicting lock exists.
l_whence Defines the starting offset. The value of this field indicates the point from which the relative offset, the l_startfield, is measured. Possible values are:
SEEK_SET
The relative offset is measured from the start of the file.
SEEK_CUR
The relative offset is measured from the current position.
SEEK_END
The relative offset is measured from the end of the file.

These values are defined in the unistd.h file.

l_start Defines the relative offset in bytes, measured from the starting point in the l_whence field.
l_len Specifies the number of consecutive bytes to be locked.
l_sysid Contains the ID of the node that already has a lock placed on the area defined by the fcntlsubroutine. This field is returned only when the value of the Command parameter isF_GETLK.
l_pid Contains the ID of a process that already has a lock placed on the area defined by thefcntl subroutine. This field is returned only when the value of the Command parameter isF_GETLK.

l_vfs

Specifies the file system type of the node identified in the l_sysid field.

 举例说明:在嵌入式编程中经常会遇到写配置文件的问题,这个时候由于多进程操作就需要跟配置文件加写锁操作。

int cfg_save()
{
	int fd = -1;
	struct flock lock;
	struct stat stat_buf;
	char *p = NULL;
	char description[200] = {0};

	fd = open(cfg_file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
	if (fd == -1)
	{
		sprintf(description,"open error %s.", cfg_file);
		write_log(time(NULL), SER_ERR, CFG_LOG, "cfg_func", "cfg_save",description);
		return -1;
	}
	/* Set a write lock */
	lock.l_type = F_WRLCK;
	lock.l_start = 0;
	lock.l_whence = SEEK_SET;
	lock.l_len = 0;
	if (fcntl(fd, F_SETLKW, &lock) == -1 || fstat(fd, &stat_buf) == -1) 
	{
		close(fd);
		fprintf(stderr,"lock cfg_file error\n");
		return -1;
	}
	
	save_to_tree();
	
	if(tree == NULL)
	{
		fprintf(stderr,"cfg_save  error\n");
		write_log(time(NULL), SER_ERR, CFG_LOG, "cfg_func", "cfg_save","cfg_save  error.");
		close(fd);
		return -1;
	}
	mxmlSaveFd(tree, fd, whitespace_cb);//把值写入配置文件
	if (tree!=NULL) 
	{
		mxmlDelete(tree);
		tree = NULL;
	}
	close(fd);
	return 0;
}



 类似资料: