POSIX Advisory Lock

POSIX Advisory Lock is a lock that doesn’t necessary forbid other process from writting the file that is being locked. It is especially useful when working with cooperating processes. It could be done with flock() Unix System Call#, imported from sys/file.h, with File Descriptor# and specified operation as parameters.

There are four operation flags could be used:

  • LOCK_SH places a shared lock which could be owned by multiple processes
  • LOCK_EX places an exclusive lock
  • LOCK_NB imposes non-blocking policy on the lock when ORed with another lock flag
  • LOCK_UN remove the current lock held by the process

An example use case is shown as follows:

int fd = open("hello.txt", ...);

if (flock(fd, LOCK_SH) == -1) { // acquire a shared lock
  perror("lock");
}

// Do stuffs (criticial section)

if (flock(fd, LOCK_UN) == -1) { // relinguish the lock
  perror("lock");
}
Links to this page
#unix #linux #parallelism #operating-system