///////////////////////////////////////////////////////////////////////////// // Creation 11/12/2003 // // // LOCKDEMO.C // ---------- // // // Sylvain MARECHAL - sylvain.marechal1@libertysurf.fr ///////////////////////////////////////////////////////////////////////////// // // Show how to lock a file under Unix, using fcntl() // ///////////////////////////////////////////////////////////////////////////// #include #include #include #include #include /* l_type => F_RDLCK = 0 F_WRLCK = 1 F_UNLCK = 2 */ int main(int argc, char *argv[]) { /* l_type l_whence l_start l_len l_pid */ struct flock fl = { F_WRLCK, SEEK_SET, 0, 0, 0 }; int fd, fd2, fd3; fl.l_pid = getpid(); if (argc > 1) fl.l_type = F_RDLCK; if ((fd = open("lockdemo.c", O_RDWR)) == -1) { perror("open"); exit(1); } if ((fd2 = open("lockdemo.c", O_RDWR)) == -1) { perror("open"); exit(1); } printf( "Reading lock information ...\n" ); fl.l_pid = 1; if (fcntl(fd2, F_GETLK, &fl) == -1) { perror("fcntl"); exit(1); } printf("lock information : (l_type=%d, l_whence=%d, l_start=%d, l_len=%d, l_pid=%d)\n", fl.l_type, fl.l_whence, fl.l_start, fl.l_len, fl.l_pid); fl.l_type = F_WRLCK; printf("Press to try to get lock: "); getchar(); printf("Trying to get lock..."); if (fcntl(fd, F_SETLKW, &fl) == -1) { perror("fcntl"); exit(1); } printf("got lock (l_type=%d, l_whence=%d, l_start=%d, l_len=%d, l_pid=%d)\n", fl.l_type, fl.l_whence, fl.l_start, fl.l_len, fl.l_pid); printf( "Reading lock information ...\n" ); if ((fd3 = open("lockdemo.c", O_RDWR)) == -1) { perror("open"); exit(1); } fl.l_type = F_WRLCK; fl.l_pid = 2; if (fcntl(fd3, F_GETLK, &fl) == -1) { perror("fcntl"); exit(1); } printf("lock information : (l_type=%d, l_whence=%d, l_start=%d, l_len=%d, l_pid=%d)\n", fl.l_type, fl.l_whence, fl.l_start, fl.l_len, fl.l_pid); printf("Press to release lock: "); getchar(); fl.l_type = F_UNLCK; /* set to unlock same region */ if (fcntl(fd, F_SETLK, &fl) == -1) { perror("fcntl"); exit(1); } printf("Unlocked.\n"); close(fd); }