file locking problem

utzoo!decvax!ucbvax!ihnss!houxi!houxg!lime!martin utzoo!decvax!ucbvax!ihnss!houxi!houxg!lime!martin
Sat Jan 30 17:42:39 AEST 1982


#define	lock(f)	close(open(f,O_CREAT|O_EXCL))
#define	unlock(f)	unlink(f)
#define	locked(f)	access(f,0)

i use these (on UNIX 3.0) to control locking for a lineprinter daemon.
sample code:-

	while( lock(LOCK) == FAIL )
		sleep(4);

	close(lineprinter);
	unlock(LOCK);

	if( !locked(LOCK) )
		fprintf(stderr,"printer in use\n");

where FAIL = -1

		martin levy HO(201-949)-2787

NOTE:- O_CREAT|O_EXCL will create the file if it does not exist, but O_EXCL
	makes the open() fail if the file exists!. so it only works if the
	file does not exist. QED.



More information about the Comp.unix.wizards mailing list