#include #include #include #include #include #include /* Your basic Stevens cut-and-paste */ static int lock_reg (int fd, int cmd, int type, off_t offset, int whence, off_t len) { struct flock lock; lock.l_type = type; /* F_RDLCK, F_WRLCK, F_UNLCK */ lock.l_start = offset; /* byte offset relative to whence */ lock.l_whence = whence; /* SEEK_SET, SEEK_CUR, SEEK_END */ lock.l_len = len; /* #bytes, 0 for eof */ return fcntl (fd, cmd, &lock); } #define lock_entire_file(fd) \ lock_reg ((fd), F_SETLK, F_WRLCK, 0, SEEK_SET, 0) #define unlock_entire_file(fd) \ lock_reg ((fd), F_SETLK, F_UNLCK, 0, SEEK_SET, 0) int main (int argc, char **argv) { int result; int fd; if (argc != 2) { fprintf (stderr, "Must pass in a single file to lock\n"); return 1; } fd = open (argv[1], O_RDWR); if (fd < 0) { fprintf (stderr, "Failed to open '%s': %s\n", argv[1], strerror (errno)); return 1; } result = lock_entire_file (fd); if (result < 0) { fprintf (stderr, "Failed to lock '%s': %s\n", argv[1], strerror (errno)); return 1; } printf ("Successfully locked '%s', unlocking and exiting\n", argv[1]); close (fd); return 0; }