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:
If the value of the Command parameter to the fcntl subroutine is F_GETLK, the l_typefield describes an existing lock. Possible values are:
|
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:
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;
}