Atomic file truncation

William Kucharski kucharsk at uts.amdahl.com
Sat May 13 14:23:55 AEST 1989


This was posted before in a discussion about providing a work-alike of BSD 
ftruncate(2) in SYSV, but here goes again:

The routine depends on the undocumented fcntl F_FREESP, which is present in
SVR3.1 and above.  The fcntl frees file space starting at the location
indicated by fl.l_start.

#include <sys/types.h>
#include <fcntl.h>

int
truncate(fd, length)
int	fd;
off_t	length;
{
	struct flock	fl;

	/* truncate file to length <length> */

	fl.l_whence = 0;
	fl.l_len = 0;
	fl.l_start = length;	/* make offset "start" the new EOF */
	fl.l_type = F_WRLCK;	/* why not write lock it? */

	if (fcntl(fd, F_FREESP, &fl) < 0)
		return(-1);

	return(0);
}


-- 
					William Kucharski

ARPA: kucharsk at uts.amdahl.com
UUCP: ...!{ames,decwrl,sun,uunet}!amdahl!kucharsk

Disclaimer:  The opinions expressed above are my own, and may not agree with
	     those of any other sentient being, not to mention those of my 
	     employer.  So there.



More information about the Comp.unix.wizards mailing list