a portable way to truncate an open file

Richard Kuhns rjk at sawmill.UUCP
Thu May 11 03:54:46 AEST 1989


I've got the strong feeling that this is something that should be
obvious and straight-forward, but for the life of me I can't think
of a *portable* way to do it.

The scenario:  I have a process which should only be run by one person
at a time.  I also want to record the progress of this process in a
datafile with a name that is constant across all invocations of this
process (I don't want to use a different name a la mktemp(3C) each
time).  I'd like to do the following:

	open the file (for writing);
	try to lock the file exclusively;
	if (I can't)
	    tell user someone else is running this program;
	    exit;
	endif
	truncate the file (size 0);	<--- how do I do this?
	start writing;

Under BSD, I can [f]truncate() it, but I can't think of a good way
to do it under System V, and the code has to run there too.  I can't
do the truncate as part of the [f]open(), since I don't have the lock
yet.

This sounds like it could be useful for people other than myself, so
feel free to post responces (unless you REALLY enjoy sending mail...;-)).

TIA

Rich Kuhns
pur-phy!sawmill!rjk



More information about the Comp.unix.questions mailing list