Unix environment variable-file record lock

When the first process is reading or modifying a certain part of the file, using the record lock can prevent other processes from modifying the same file area. The lock operation is performed through the fcntl function.

int fcntl(int fd, int cmd, struct flock *lock);

Parameters: cmd: F_GETLK: used to detect whether an existing lock will prevent the granting of a new lock to the calling process. If there is no such lock, the l_type member of the flock structure pointed to by the lock will be set to F_UNLCK, otherwise it already exists The lock information will be written into the flock structure pointed to by lock (non-atomic operation)

                        F_SETLK: Acquire or release the lock described by the lock pointed to by the flock structure. If the lock cannot be acquired, the function will immediately return an EACESS or EAGAIN error without blocking.

                        F_SETLKW: Block acquiring a lock

The structure of struct flock is as follows:

struct flock {

      short l_type;    /* 锁的类型: F_RDLCK, F_WRLCK, F_UNLCK */

      short l_whence;  /* 加锁的起始位置:SEEK_SET, SEEK_CUR, SEEK_END */

      off_t l_start;  /* 加锁的起始偏移,相对于l_whence */

      off_t l_len;    /* 上锁的字节数*/

      pid_t l_pid;    /* 已经占用锁的PID(只对F_GETLK 命令有效) */

      /*...*/

};

Summary: (1) The same process can lock the same file interval and still obtain the lock permission;

(2) When a process terminates, all the record locks it established will be released;

(3) When a file descriptor is closed, any lock on the file referenced by the process through the file descriptor will be released.

(4) The child process spawned by fork does not inherit the lock set by the parent process .

(5) After executing exec , the new program can inherit the lock of the original executing program .

(6) The priority of the write lock process and the read lock process are responded to by the FIFO request sequence process.

 

Guess you like

Origin blog.csdn.net/Chiang2018/article/details/105418724