#include #include #include int fd; void lock_file() { struct flock lock; int ret; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_type = F_WRLCK; printf ("locking file\n"); fflush(stdout); ret = fcntl(fd, F_SETLKW, &lock); if (ret < 0) { perror ("lock failed:"); exit(1); } } void unlock_file() { struct flock lock; int ret; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_type = F_UNLCK; printf ("unlocking file\n"); fflush(stdout); ret = fcntl(fd, F_SETLKW, &lock); if (ret < 0) { perror ("unlock lock failed:"); exit(1); } } main(int argc, char *argv[]) { char buf[1024]; fd = open(argv[1], O_RDWR); if (fd < 0) { perror ("open failed:"); exit(1); } while(1) { lock_file(); printf ("File locked\n"); fflush(stdout); fgets(buf, sizeof(buf), stdin); unlock_file(); printf ("File unlocked\n"); fflush(stdout); } }