#include #include #include #include static void lock(int fd, const char *where, const char *expected) { struct flock lf = { .l_type = F_WRLCK, 0 }; int err = fcntl(fd, F_SETLK, &lf); if (err < 0) fprintf(stderr, "lock failed in %s (%sexpected) %d\n", where, expected, errno); } static void unlock(int fd, const char *where, const char *expected) { struct flock lf = { .l_type = F_UNLCK, 0 }; int err = fcntl(fd, F_SETLKW, &lf); if (err < 0) fprintf(stderr, "unlock failed in %s (%sexpected) %d\n", where, expected, errno); } int main(int argc, char**argv) { // int fd = open("foo", O_WRONLY | O_CREAT); int fd = fileno(fopen("foo", "w")); int err, pid = fork(); if (pid < 0) { fprintf(stderr, "fork error\n"); return -1; } // in child if (pid == 0) { lock(fd, "child", "not "); sleep(2); unlock(fd, "child", "not "); _exit(0); } sleep(1); lock(fd, "parent", ""); // file isn't locked in child, but there should not be an error on cygwin unlock(fd, "parent", "not "); sleep(2); return 0; }