20 Oct 2014

What is file locking setting clearing demo program summary

1. File Locking

1.1. Setting a lock

The fcntl() function does just about everything on the planet, but we'll just use it for file locking. Setting the lock consists of filling out a struct flock (declared in fcntl.h) that describes the type of lock needed, open()ing the file with the matching mode, and calling fcntl() with the proper arguments, comme ça:
struct flock fl;
int fd;
 fl.l_type   = F_WRLCK;  /* F_RDLCK, F_WRLCK, F_UNLCK    */
fl.l_whence = SEEK_SET; /* SEEK_SET, SEEK_CUR, SEEK_END */
fl.l_start  = 0;        /* Offset from l_whence         */
fl.l_len    = 0;        /* length, 0 = to EOF           */
fl.l_pid    = getpid(); /* our PID                      */

fd = open("filename", O_WRONLY);

fcntl(fd, F_SETLKW, &fl);  /* F_GETLK, F_SETLK, F_SETLKW */
What just happened? Let's start with the struct flock since the fields in it are used to describe the locking action taking place. Here are some field definitions:How To Become Expert In Linux/Unix

No comments:

Post a Comment