Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ fcntl file locking function add     - Linux firewall iptables beginner tutorial (Linux)

- Linux system versions organize local root password cracking method (Linux)

- High-performance JavaScript reflows and repaints (Programming)

- Understand the security restore accidentally deleted critical system files (Linux)

- To install Spotify in Ubuntu / Mint (Linux)

- Linux operation and maintenance of the actual file system, file links (Linux)

- Python exception summary (Programming)

- Linux tmux tcpdump summary (Linux)

- Making Linux root file system problems on-link library (Programming)

- OpenGL Superb Learning Notes - GLSL language foundation (Programming)

- Analysis of potential problems through custom Orabbix monitoring Oracle (Database)

- CentOS iptables firewall configuration (Linux)

- PostgreSQL 9.3.2 Json type of use (Database)

- Under Linux using Magent + Memcached cache server cluster deployment (Server)

- Python dictionary applications get built-in method (Programming)

- Piostat - Monitoring and Statistics Linux process (Linux)

- Oracle 12c PDB Analysis (Database)

- How to configure SNMPv3 on Ubuntu, CentOS and Cisco systems (Linux)

- Automatic batch resolve dependencies problem locally installed rpm package (Linux)

- Build a super simple "hardware" firewall router (Linux)

 
         
  fcntl file locking function add
     
  Add Date : 2018-11-21      
         
         
         
  File locking is atomic in nature, it can be used for inter-process synchronization file operations. In Linux, there are three functions can file locking process, namely fcntl, flock, lockf. Just say here that fcntl, its use is also the most complex.

fcntl is a file control acronym. In most of the equipment under linux is a file, so fcntl function more, including:

Duplicating a file descriptor (copy file descriptor)
File descriptor flags (operating close-on-exec flag)
File status flags (action file O_RDONLY, O_WRONLY, O_RDWR, O_APPEND, O_NONBLOCK, O_SYNC and O_ASYNC identification)
Advisory locking (advisory locks)
Mandatory locking (compulsory lock)
Managing signals (management signals)
Leases (Rental Lock)
File and directory change notification (dnotify) (files and directories to change the message)
Changing the capacity of a pipe (pipe size change)
Here only talk about Advisory locking and Mandatory locking. Advisory refers to the file lock is locked, only set up a lock logo on the file. Other processes when the file operation process, can detect the presence of the lock, but the lock does not stop its operation in this document. This is like traffic lights, when the red light, telling you not to cross the road, but if you must pass, you can not stay. When the lock is mandatory to file locking, while other processes are not compatible to this file process operations (as a read lock, write another process), the kernel will block the subsequent process until the first process unlock the lock. In this function, the function prototype for the fcntl:

#include < unistd.h>
#include < fcntl.h>

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

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
                                  (F_GETLK only) * /
              ...
          };

Advisory locking There are three operations, namely F_GETLK, F_SETLK, F_SETLKW. Wherein F_GETLK used to test the lock, note the test and not get lock; F_SETLK used to lock, unlock; F_SETLKW function with F_SETLK, just blocking the operation becomes. The fcntl can be used l_whence, l_start, l_len to control file locking range. Here are locked test lock code.

/ * Slock.c * /

#include < unistd.h>
#include < fcntl.h>
#include < sys / types.h>
#include < sys / stat.h>

int main ()
{
    struct flock _lock;

    _lock.l_type = F_WRLCK;
    _lock.l_whence = SEEK_SET;
    _lock.l_start = 0;
    _lock.l_len = 0;

    int fd = open ( "/ dev / shm / test", O_CREAT | O_RDWR, S_IRWXU | S_IRGRP | S_IWGRP | S_IRWXO);
    if (fd < 0)
    {
        puts ( "open error");
        return 0;
    }

    int ret = fcntl (fd, F_SETLK, & _ lock);
    if (ret < 0)
    {
        puts ( "fcntl error");
        close (fd);
        return 0;
    }

    puts ( "sleep now ...");
    sleep (100);
    puts ( "exit ...");
    
    _lock.l_type = F_UNLCK;
    _lock.l_whence = SEEK_SET;
    _lock.l_start = 0;
    _lock.l_len = 0;

    ret = fcntl (fd, F_SETLK, & _ lock);
    if (ret < 0)
    {
        puts ( "unlock error");
    }

    close (fd);
}

/ * Glock.c * /

#include < unistd.h>
#include < fcntl.h>
#include < sys / types.h>
#include < sys / stat.h>
#include < stdio.h>

int main ()
{
    struct flock _lock;

    _lock.l_type = F_RDLCK;
    _lock.l_whence = SEEK_SET;
    _lock.l_start = 0;
    _lock.l_len = 0;

    int fd = open ( "/ dev / shm / test", O_RDWR);
    if (fd < 0)
    {
        perror ( "open error");
        return 0;
    }

    int ret = fcntl (fd, F_GETLK, & _ lock);
    if (ret < 0)
    {
        perror ( "fcntl error:");
        close (fd);
        return 0;
    }

    printf ( "lock is% d \ n", _ lock.l_type);

    close (fd);
}

In the above code, "_ lock.l_type = F_RDLCK;" indicates the file to read shared lock, "_ ​​lock.l_whence = SEEK_SET;" represents the beginning of the file locking, "_ lock.l_start = 0;" represents the offset l_whence How many byte lock, "_ ​​lock.l_len = 0;" indicates the number of bytes locked, the length (Specifying 0 for l_len has the special meaning: lock all bytes starting at the location specified by l_whence and l_start through to the end of file, no matter how large the file grows.).

In the above code, were compiled into slock, glock. First run slock run glock:

./slock
sleep now ...
./glock
lock is 1
exit ...

slock give the file a write lock, and then test whether glock shared locks can be read together with the test results is a write lock already exists (F_WRLCK, debian definition 1). It should be noted that F_GETLK test whether the lock can be added, if so, the struct flock of l_type is F_UNLCK; if not, the current lock l_type file type, and is locked l_pid process pid. Therefore, if the lock is on slock F_RDLCK, glock test lock is F_RDLCK, both locks are compatible, l_type return type is F_UNLCK. That you can not F_GETLK to determine whether the file is locked, the lock can only be tested if a plus.

The above recommendations of the lock, if you want to achieve mandatory locks, then:

To make use of mandatory locks, mandatory locking must be enabled both on the filesystem that contains the file to be locked, and on the file itself. Mandatory locking is enabled on a filesystem using the "-o
mand "option to mount (8), or the MS_MANDLOCK flag for mount (2). Mandatory locking is enabled on a file by disabling group execute permission
on the file and enabling the set-group-ID permission bit (see chmod (1) and chmod (2)).

That is to say, to achieve the mandatory lock shall file with the file system to mount the "-o mand" parameter, and use the function chmod x file permissions user group removed. Then use the same code on top of it. The first time I see such a peculiar function, a function is not by itself achieve the parameters of control, but the system is set ..... Luckily I do not have a mandatory lock.

The above is a simple example plus fcntl file locking. Note that the realization of the different systems are not the same, not the same macro definition. Such as:

 / * Record locking flags (F_GETLK, F_SETLK, F_SETLKW) * /
#define F_RDLCK 1 / * shared or read lock * /
#define F_UNLCK 2 / * unlock * /
#define F_WRLCK 3 / * exclusive or write lock * /

In the debian, / usr / include / bits / fcntl.h
/ * For posix fcntl () and `l_type 'field of a` struct flock' for lockf (). * /
#define F_RDLCK 0 / * Read lock. * /
#define F_WRLCK 1 / * Write lock. * /
#define F_UNLCK 2 / * Remove lock. * /
     
         
         
         
  More:      
 
- Modifying the system registry protection server security (Linux)
- Online booking shocking information leakage risk, you dare book the tickets online? (Linux)
- Linux serial port driver test (Linux)
- Use GLOBK batch command network adjustment (Linux)
- Ten minutes to find out the character set and character encoding (Linux)
- CentOS7 installation hardware monitoring for Zabbix enterprise applications (Server)
- Linux, MySQL root privilege escalation another method (Linux)
- The simple multi-threaded Python (Programming)
- Yii2 Advanced Version Copy New Project Problem Solved (Programming)
- Forgot Linux root password (Linux)
- Use Visual Studio 2015 to develop Android program (Programming)
- How Ubuntu Snappy Core 2 running on Raspberry Pi (Linux)
- Single-node Hadoop environment to build (Server)
- MySQL log from the library than the main library (Database)
- Ten SCP transfer command example (Linux)
- MySQL uses Federate engine mapping table to achieve operation of the local remote operation table (Database)
- libreadline.so.6: can not open shared object file problem solution (Linux)
- Linux platform NTOP Installation and Configuration (Linux)
- The Java ThreadLocal (Programming)
- How to Install Apache on Linux servers (Server)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.