Linux File lock learning notes

Source: Internet
Author: User

I have read "Advanced Programming for UNIX environments" before, but I have no in-depth understanding and learning about the concept of File locks. Recently, I encountered a deadlock when operating MySQL databases. By the way, I think of File locks in Linux. The library in the database is supported by files in the OS. For this reason, I need to learn more about Linux File locks.

In Linux, file locks are divided into advisory locks and mandatory locks ). Most of the file locks used in Linux are recommended locks, and you need to check whether the system supports the force lock when using the force lock ). Opensuse11.1,
Centos5.3 and other systems do not support forced file locks.

The following briefly introduces the recommended locks and forced locks:

1,
The recommended locks are also called collaborative locks. For this type of lock, the kernel only provides addition and subtraction locks and checks for locking operations, but does not provide lock control and coordination. That is to say, if the application does not detect whether to lock a file or write data directly to the file regardless of the lock, the kernel will not block the control. Therefore, it is recommended to lock the process, instead of blocking operations on the file. Instead, you can only rely on the conscious detection of locking and then constrain your behavior;

2,
The forced lock is the file lock of the OS kernel. During file operations, such as open, read, and write operations, the OS checks whether the file is locked forcibly. If the file is locked, the operation fails. That is, the kernel forces applications to comply with game rules;

 

 

Introduction to functions related to file lock operations:

Flock, fcntl, and flock mainly implement the recommended lock. Of course, you can also use fcntl to complete the recommended lock. In addition to the recommended lock, fcntl can also complete the record lock, that is, locking part of the file;

 

Implicit inheritance and release of locks

Rules for automatic inheritance and release of record locks:

1,
Locks are related to processes and files. Two meanings: when a process terminates, all the locks it creates are released. Second, when a descriptor is disabled at any time, any lock on the file that the process can reference through this descriptor is released (these locks are set by this process ). This means:

Fd1 = open (pathname ,....);

Read_lock (fd1 ,...);

Fd2 = DUP (fd1 );

Close (fd2 );

After close (fd2), all the locks set on fd1 are released. If DUP is replaced with open to open the same file on another descriptor, the effect is the same;

2,
The child process generated by fork does not inherit the lock set by the parent process. This means that if a process gets a lock and then calls fork, the sub-process is regarded as another process for obtaining the lock from the parent process. For any descriptor inherited from the parent process, the sub-process must call fcntl to obtain its own lock. This is consistent with the role of the lock. The lock is used to prevent multiple processes from simultaneously operating on the same file. If the child process inherits the lock of the parent process, the Parent and Child processes operate on the same file, which is contrary to the original intention of the lock;

3,
After exec is executed, the new program can inherit the lock of the original execution program. However, if the close-on-exec flag is set for a file descriptor, all the locks of the corresponding file will be released when the file descriptor is closed as part of exec.

 

Appendix: code used to check whether the system supports forced lock (Advanced Programming in UNIX environment);

 

# Include <sys/types. h>

# Include <sys/STAT. h>

# Include <sys/Wait. H>

# Include <stdarg. h>

# Include <stdio. h>

# Include <unistd. h>

# Include <string. h>

# Include <errno. h>

# Include <stdlib. h>

# Include <fcntl. h>

# Include <signal. h>

# Include <sys/Wait. H>

 

Volatile sig_atomic_t sigflag;

Int pfd1 [2], pfd2 [2];

Sigset_t
Newmask, oldmask, zeromask;

 

Void err_doit (INT errnoflag, const char * FMT,
Va_list AP)

{


Int errno_save;


Char Buf [4096];


Errno_save = errno;


Vsprintf (BUF, FMT, AP );


If (errnoflag)


Sprintf (BUF + strlen (BUF), ": % s", strerror (errno_save ));


Strcat (BUF, "/N ");


Fflush (stdout );


Fputs (BUF, stderr );


Fflush (stderr );


Return;

}

 

Void err_sys (const char * FMT ,...)

{


Va_list AP;


Va_start (AP, FMT );


Err_doit (1, FMT, AP );


Va_end (AP );


Exit (1 );

}

Void sig_usr (INT signo)

{


Sigflag = 1;


Return;

}

Tell_wait ()

{


If (signal (SIGUSR1, sig_usr) = sig_err)/* SIGUSR1 is a user-defined signal */


Err_sys ("signal (SIGINT) error ");


If (signal (sigusr2, sig_usr) = sig_err)


Err_sys ("signal (sigquit) error ");


Sigemptyset (& zeromask );


Sigemptyset (& newmask );


Sigaddset (& newmask, SIGUSR1 );


Sigaddset (& newmask, sigusr2 );


/* Block SIGUSR1 and sigusr2 and save the current signal mask */


If (sigprocmask (sig_block, & newmask, & oldmask) <0)


Err_sys ("sig_block error ");

}

 

Void wait_parent (void)

{


While (sigflag = 0)


Sigsuspend (& zeromask );
/* Suspend () cancels all signal shielding and waits for the signal from the parent process */


Sigflag = 0;


/* Recover the signal mask */


If (sigprocmask (sig_setmask, & oldmask, null) <0)


Err_sys ("sig_setmask error ");

}

 

 

Int lock_reg (int fd, int cmd, int type,
Off_t offset, int whence, off_t Len)

{


Struct flock lock;


Lock. l_type = type;


Lock. l_start = offset;


Lock. l_whence = whence;


Lock. l_len = Len;


Return (fcntl (FD, CMD, & lock ));

}

 

Void set_fl (int fd, int flags)

{


Int val;


If (val = fcntl (FD, f_getfl, 0) <0)


Err_sys ("fcntl f_getfl error ");

 


Val | = flags;/* flag */

 


If (fcntl (FD, f_setfl, Val) <0)


Err_sys ("fcntl f_setfl error ");

}

 

Void err_ret (const char * FMT ,...)

{


Va_list AP;


Va_start (AP, FMT );


Err_doit (1, FMT, AP );

Va_end (AP );


Return;

}

 

 

Int main (void)

{


Int FD;


Pid_t PID;


Char buff [5];


Struct stat statbuf;


If (FD = open ("templock", o_rdwr | o_creat | o_trunc, 0644 ))
<0)


Err_sys ("Open error", buff );


If (write (FD, "abcdef", 6 )! = 6)


Err_sys ("write error ");

 


/* Open
Set-group-ID (S-gid), and disable the group execution permission */


If (fstat (FD, & statbuf) <0)


Err_sys ("fstat error ");


If (fchmod (FD, (statbuf. st_mode &~ S_ixgrp) | s_isgid) <0)


Err_sys ("fork error ");


Tell_wait ();


If (pid = fork () <0 ){


Err_sys ("fork error ");

}
Else if (pid> 0) {/* parent process */

/* Entire file write lock */


If (lock_reg (FD, f_setlk, f_wrlck, 0, seek_set, 0) <0)


Err_sys ("write_lock error ");


Kill (PID, SIGUSR1);/* sends a signal to the sub-process to inform the lock completion */


If (waitpid (PID, null, 0) <0)


Err_sys ("waitpid error ");

}
Else {


Wait_parent ();/* Wait for the parent process to set the lock */


Set_fl (FD, o_nonblock );


If (lock_reg (FD, f_setlk, f_rdlck, 0, seek_set, 0 )! =-1)


Err_sys ("Child: read_lock succeeded ");


Printf ("read_lock of already-locked region return % d/N ",
Errno );

 


If (lseek (FD, 0, seek_set) =-1)


Err_sys ("lseek, error ");

 


If (read (FD, buff, 2) <0)

Err_ret ("read
Failed (mandatory locking wroks )");


Else


Printf ("read OK (no mandatory locking), buff = % 2.2 S/N ",
Buff );

}


Exit (0 );

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.