Featured Post

Monday, August 1, 2016

File locking in UNIX


    When a file can be accessed by more then one process at a time then synchronization problem occurs. For example if one process trying to write data to a file, at the same time other process trying to read the content of a file then wrong data may be read. File Locking mechanism provides coordination between two processes when they sharing the common file or file region.

They are two of locking mechanisms:

Mandatory Locking: Mandatory locks works between cooperative and non cooperative processes.

Advisory Locking: Advisory Locks works between cooperative process. They are two types of advisory locks: read locks and write locks.

                                                                cjuschools.blogspot.in

Many earlier versions on UNIX supports file locking using lockf() system call. Latest versions of UNIX support flock() system call. The drawback in flock() system call is it can lock entire file but it is not useful in locking a file region.

flock structure:
            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 locking our lock */
             };

l_type: It can be R_RDLCK, F_WRLCK or F_UNLCK stands for read lock, write lock or clear the clock respectively.

l_whence: This field determines where the l_start starts from.It can be either SEEK_SET OR SEEK_CUR OR SEEK_END for beginning of file or current file posistion or end of file respectively.

l_start: Specifies the starting offset in bytes of the block, relative to l_whence.

l_len; This is the length of the region to be locked in bytes.

l_pid: Process ID of the process dealing with the lock.

example:

fd=open("file_name",O_WRONLY); /* file opened in write mode */

 struct flock f1;

f1.l_type=F_WRLCK;
f1.l_whence=SEEK_SET;
f1.l_start=0
f1.l_len=0;
f1.l_pid=getpid();

fcntl(fd, F_SETLKW, &f1);
  

No comments:

Post a Comment