#include #include #include #include #include #include #include int lock_file(int fd, int l_options) { int ret; ret = flock(fd, l_options); if (ret) perror("flock error"); return ret; } int main() { int fd; char *filename = "/tmp/lockf1"; pid_t pid; int syncpipe[2]; char c; pipe(syncpipe); fd = open(filename, O_CREAT | O_RDWR, 0666); if(fd < 0) { perror("parent could not open file"); exit(1); } pid = fork(); if(pid < 0) { perror("fork failed"); exit(1); } if (pid) { lock_file(fd, LOCK_EX); if (close(fd)) perror("parent: error closing file"); write(syncpipe[1], &c, 1); } else { /* Wait until the parent has taken the lock */ read(syncpipe[0], &c, 1); lock_file(fd, LOCK_UN); lock_file(fd, LOCK_EX); if(close(fd)) perror("child: error closing file"); exit(0); } wait(NULL); return 0; }