// Ivan Novick // Aug 26, 2009 // Advisory Locking on a file #include #include #include #define BUFSIZE 64 int main(int argc, char** argv){ int fd = open("data_file", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR); if (fd < 0) { fprintf(stderr, "failed opening file with error code %d\n", fd); return 1; } pid_t pid = getpid(); char buf[BUFSIZE] = {0}; // initialize to all zeros sprintf(buf, "%u\n", pid); struct flock lock; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int i; for (i = 0; i < 10; ++i){ // lock the file lock.l_type = F_WRLCK; if (fcntl(fd, F_SETLKW, &lock) == -1){ fprintf(stderr, "error taking write lock on the file\n"); return 1; } fprintf(stdout, "file is locked for writing by %u\n", pid); fflush(stdout); // just write the pid id in the beginning of the file lseek(fd, 0, SEEK_SET); write(fd, buf, BUFSIZE); sleep(5); // sleep for demo purpose to show the file is locked by this process // unlock the file lock.l_type = F_UNLCK; if (fcntl(fd, F_SETLKW, &lock) == -1){ fprintf(stderr, "error unlocking the file\n"); return 1; } fprintf(stdout, "file is unlocked by %u\n", pid); fflush(stdout); sleep(1); } return 0; }