flock - apply or remove an advisory lock on an open file
#include <sys/file.h> int flock(int fd, int operation)
Apply or remove an advisory lock on an open file. The file is specified by fd. Valid operations are given below:
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
4.4BSD (the flock(2) call first appeared in 4.2BSD).
flock(2) does not lock files over NFS. Use fcntl(2) instead: that does work over NFS, given a sufficiently recent version of Linux and a server which supports locking.
flock(2) and fcntl(2) locks have different semantics with respect to forked processes and dup(2).
/*
- This program creates and locks /tmp/flock.example, waiting for the user
- before unlocking the file again.
*
- By running this program twice simultaniously, locking can be demonstrated.
*
- /
- include <sys/file.h> /* for flock(2) */
- include <sys/stat.h> /* for S_* constants */
- include <string.h> /* for strerror(3) prototype */
- include <stdio.h> /* for fprintf(3),printf(3),stderr protype */
- include <errno.h> /* for errno prototype */
- include <unistd.h> /* for close(2) prototypes */
- define FILENAME "/tmp/flock.example"
int main(int argc,char **argv) {
int fd; char buf;
fd = open(FILENAME,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR); if (fd==-1) {
fprintf(
stderr, "open(\"%s\",O_RDWR,S_IRUSR|S_IWUSR): %s (%i)\n", FILENAME, strerror(errno), errno);
return 1;
}
printf("Aquiring lock..."); fflush(stdout);
/* Aquire an exclusive lock */ if (flock(fd,LOCK_EX) == -1) {
fprintf(
stderr, "flock(fd,LOCK_EX): %s (%i)\n", strerror(errno), errno);
return 1;
} printf("Succeeded!\n");
printf("Press enter to release the lock.\n");
if (read(0,&buf,sizeof(buf)) == -1) {
printf("read(0,&buf,sizeof(buf)): %s (%i)\n",
strerror(errno), errno );
return 1;
}
printf("Releasing lock..."); fflush(stdout);
if (flock(fd,LOCK_UN)==-1) {
fprintf(
stderr, "flock(fd,LOCK_UN): %s (%i)\n", strerror(errno), errno);
return 1;
}
printf("Released!\n");
if (close(fd)==-1) {
fprintf(
stderr, "close(fd): %s (%i)\n", strerror(errno), errno);
return 1;
}
return 0;
}
open(2), close(2), dup(2), execve(2), fcntl(2), fork(2), lockf(3)
There are also locks.txt and mandatory.txt in /usr/src/linux/Documentation.
15 pages link to flock(2):