Skip to content
Snippets Groups Projects
Commit b5deadbe authored by Ahmed Abd El Mawgood's avatar Ahmed Abd El Mawgood
Browse files

Add (POSIX defined) struct flock

struct flock is posix defined locking mechanism on *nix platform

Example usage (copied from https://gavv.github.io/articles/file-locks/) :

  #include <fcntl.h>

  struct flock fl;
  memset(&fl, 0, sizeof(fl));

  // lock in shared mode
  fl.l_type = F_RDLCK;

  // lock entire file
  fl.l_whence = SEEK_SET; // offset base is start of the file
  fl.l_start = 0;         // starting offset is zero
  fl.l_len = 0;           // len is zero, which is a special value representing end
                        // of file (no matter how large the file grows in future)

  fl.l_pid = 0; // F_SETLK(W) ignores it; F_OFD_SETLK(W) requires it to be zero

  // F_SETLKW specifies blocking mode
  if (fcntl(fd, F_SETLKW, &fl) == -1) {
    exit(1);
  }

  // atomically upgrade shared lock to exclusive lock, but only
  // for bytes in range [10; 15)
  //
  // after this call, the process will hold three lock regions:
  //  [0; 10)        - shared lock
  //  [10; 15)       - exclusive lock
  //  [15; SEEK_END) - shared lock
  fl.l_type = F_WRLCK;
  fl.l_start = 10;
  fl.l_len = 5;

  // F_SETLKW specifies non-blocking mode
  if (fcntl(fd, F_SETLK, &fl) == -1) {
      exit(1);
  }

  // release lock for bytes in range [10; 15)
  fl.l_type = F_UNLCK;

  if (fcntl(fd, F_SETLK, &fl) == -1) {
      exit(1);
  }

  // close file and release locks for all regions
  // remember that locks are released when process calls close()
  // on any descriptor for a lock file
  close(fd);
parent e14b3e09
No related branches found
No related tags found
Loading
Loading
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment