I read that Unix like system typically use advisory locking for file IO vs mandatory locking used by Microsoft OS's. If I understood correctly in mandatory locking file lock is enforced by the OS itself. But I do not get the intuition of advisory locking. Take the example of two process,say "A" and "B" that are working on file "foo". Lets say "A" writes to "foo" and "B" reads from "foo". How would advisory locking work in this scenario? If the OS/file system is not enforcing a lock for "foo" then how is consistency maintained for reads and writes?
Advisory locking is for processes that cooperate "peacefully". The kernel keeps track of the locks but doesn't enforce them - it's up to the applications to obey them. This way the kernel doesn't need to deal with situations like dead-locks.
Mandatory locking was introduced in System V Unix, but it turns out that the design was not the brightest thing. (That is, there are ways around it.) If you need something like true mandatory locking under unixy systems, then follow a client-server design pattern where the server is the authority on the shared resource(s).
-
1Why is it called advisory? Does the kernel provide advice to the requesting process regarding who owns locks etc? – Geek Jul 30 '14 at 10:31
-
2Yes, the kernel plays a role, not by actively advising, but as countermode says, by providing the locks. These work sort of like mutexes in multi-threading: they're associated with a file the way a mutex might be associated with a variable, but if you don't check/set them, you can still access the file or variable. So the system is cooperative. Note there are reasons why mandatory file locking is actually a bad idea -- e.g., it implies potential non-cooperation with regard to shared system files, and creates the opportunity for a misbehaving app to screw a lot of things up. – goldilocks Jul 30 '14 at 10:39
man fcntl
: pubs.opengroup.org/onlinepubs/9699919799/functions/fcntl.html (POSIX) – goldilocks Jul 30 '14 at 10:44