a question on open() and lseek()

Steve Summit stevesu at copper.UUCP
Wed Apr 30 17:02:19 AEST 1986


I hate to post information that has been posted already, but
people keep implying that O_APPEND simply seeks to the end as
the file is opened.  Someone else has already posted an article
pointing this out, but, at least on 4.2bsd,

	f = open(file, O_WRONLY | O_APPEND);

is _n_o_t the same as

	f = open(file, O_WRONLY);
	lseek(f, 0, L_XTND);

If that were all it did, it would not be nearly so useful as what
it does do, which is arrange that a seek to the end of the file
happen immediately before each and every write that you ever do
to the file.  That would seem to be the same as doing

	lseek(f, 0, L_XTND);
	write(f, data, count);

The difference is that the lseek implied by O_APPEND is atomic.
That is, nobody else can do anything to the file between the time
the seek happens and the time the write happens, which would be
possible if you didn't use O_APPEND but instead did the lseek by
hand.

If you know you're the only one writing to the file, O_APPEND
doesn't do you a whole lot of good.  It saves you a bit of system
call overhead, and it makes your program a bit less portable. 
If, on the other hand, you are writing to some kind of a log file
and you know that other processes are too, O_APPEND is
indispensable.

If you use neither O_APPEND nor manual lseeks, you and the other
programs will step all over each other's data (assuming that the
file was opened separately by each process, so each file
descriptor has its own read/write pointer.  If the file was
opened once, and the other processes inherited the same file
descriptor by being forked from the process that opened it, this
case would work).

If you manually seek to the end before each write, you won't step
on the other process's data, or get stepped on yourself, except
when you lose out on race conditions when you get swapped out
after doing the lseek but before doing the write, and one of the
other processes gets swapped in and does a write.  By Murphy's
law, you won't lose on this race condition during your entire
development process, and it will happen for the first time when
your first customer uses your program for the first time.

I don't know how systems other than 4.2bsd interpret O_APPEND.
I would consider systems that implement O_APPEND in the "obvious"
way (by simply seeking to the end as the file is opened, which is
what I used to think O_APPEND did) to be marginally useful, or
downright wrong.

                                         Steve Summit
                                         tektronix!copper!stevesu



More information about the Comp.unix.wizards mailing list