ptg10805159
Section 14.3 RecordLocking 497
wrote the new contents to a temporary file, removed the original file, and then
renamed the temporary file to be the original file. The mandatory recordlocking
has no effect on theunlinkfunction, which allowed this to happen.
Under FreeBSD 8.0 and Solaris 10, we can obtain the system call trace of a process with
thetruss( 1 )command. Linux 3.2.0 provides thestrace( 1 )command for the same
purpose. Mac OS X 10.6.8 provides thedtruss(1m) command to trace system calls, but
its use requires superuser privileges.
•Thevieditor was never able to edit the file. It could read the file’s contents, but
whenever we tried to write new data to the file,EAGAINwas returned. If we
tried to append new data to the file, thewriteblocked. This behavior fromvi
is what we expect.
•Using the Korn shell’s>and>>operators to overwrite or append to the file
resulted in the error ‘‘cannot create.’’
•Using the same two operators with the Bourne shell resulted in an error for>,
but the>>operator just blocked until the mandatory lock was removed, and
then proceeded. (The difference in the handling of the append operator occurs
because the Korn shellopensthe file withO_CREATandO_APPEND,and we
mentioned earlier that specifying O_CREATgenerates an error.The Bourne
shell, however,doesn’t specifyO_CREATif the file already exists, so theopen
succeeds but the nextwriteblocks.)
Results will vary,depending on the version of the operating system you areusing. The
bottom line, as demonstrated by this exercise, is to be wary of mandatory record
locking. As seen with theedexample, it can be circumvented.
Mandatory recordlocking can also be used by a malicious user to hold a read lock
on a file that is publicly readable. This can prevent anyone from writing to the file. (Of
course, the file has to have mandatory recordlocking enabled for this to occur,which
may requirethe user to be able to change the permission bits of the file.) Consider a
database file that is world readable and has mandatory recordlocking enabled. If a
malicious user were to hold a read lock on the entirefile, the file could not be written to
by other processes.
Example
We can run the program in Figure14.12 to determine whether our system supports
mandatory locking.
#include "apue.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>
int
main(int argc, char *argv[])
{
int fd;