fcntl

fcntl针对描述符提供控制,可以用来改变已打开文件的性质

一、函数定义

函数接口定义:

text
1
2
3
4
5
6
7
8
#include <unistd.h>
#include <fcntl.h>

int fcntl(int fd, int cmd);

// 针对cmd的值,可以使用第三个参数arg/lock
int fcntl(int fd, int cmd, long arg);
int fcntl(int fd, int cmd, struct flock *lock);

函数参数结构定义:

text
1
2
3
4
5
6
7
8
9
struct flcok {
   short int l_type; /* 锁类型:F_RDLCK, F_WRLCK, F_UNLCK */
   short int l_whence; /* 锁定开始位置:SEEK_SET, SEEK_CUR, SEEK_END */
   off_t l_start; /* 锁定开始计算位置:relative starting offset in bytes */
   off_t l_len; /* 锁定长度:#bytes; 0 means EOF */
   pid_t l_pid; /* PID returned by F_GETLK */
};
// 注:开始位置是由l_whence和l_start共同指定的
// l_whence指定了l_start开始计算的位置

函数参数解释:

  • fd是要改变的描述符(已打开的文件等)
  • cmd:操作指定,包含如下几种
    • F_DUPFD:复制一个现有的描述符
    • F_GETFD/F_SETFD:获得/设置文件描述符标记
    • F_GETFL/F_SETFL:获得/设置文件状态标记
    • F_GETOWN/F_SETOWN:获得/设置异步I/O所有权
    • F_GETLKF_SETLK/F_SETLKW:获得/设置记录锁
  • arg/lock:针对cmd的值,需要的第三个参数

二、应用场景

2.1 记录上锁

记录上锁使用如下接口:

text
1
2
3
4
#include <fcntl.h>

int fcntl(int fd, int cmd, ... /* struct flock *lock */);
/* 成功返回值取决于cmd,失败返回-1 */

记录上锁使用cmd的类型:F_GETLKF_SETLK/F_SETLKW

  • F_GETLK:
  • F_SETLK:
  • F_SETLKW:

三、参考文献

【0】Unix网络编程