[net.sources.games] here is scorefile locking code for SysVR2

rcj@burl.UUCP (Curtis Jackson) (06/12/85)

Here is a crude locking mechanism for non-BSD systems.  It works
quite well, and only has a \possibility/ of screwing up if 3 or
more people try to write their score out at the exact same time
(feel free to correct me via mail if you think I'm wrong on that).
Just define LOCKFILE at the top of robots.c; here is how I defined
mine:

-----------------------------------
#ifdef RCJ
#define LOCKFILE "/tmp/robotslockfile"
#endif
-----------------------------------

Then replace the function record_score() with the two functions
rmlockf() and record_score() below; I've ifdef'd out the original
code in record_score but it is still all there in case you send
this to a BSD system with flock stuff.  REMEMBER TO DEFINE RCJ
WHEN YOU COMPILE (i.e., in your Makefile add a '-DRCJ' to the
cc command-line)!!

Oh, almost forgot.  This version allows 15 seconds of waiting for
the lockfile to be removed before deciding that the previous robots
died while trying to write the scorefile; it then forcibly removes
the lockfile and writes its own score out.  You might want to adjust
that 15 to some other number according to system load and/or taste.

-----------------------------------
#ifdef RCJ
int rmlockf(dummy)
int dummy;
{
	unlink(LOCKFILE);
}
#endif

record_score(eaten,fname,max_days,type_str)
bool	eaten;
char	*fname;
int	max_days;
char	*type_str;
{
    int			fd;
    int 		(*action)();
#ifndef RCJ
    struct flock	fl;
#endif

    action = signal(SIGINT,SIG_IGN);
#ifdef RCJ
    signal(SIGALRM,rmlockf);
#endif
    if ((fd = open(fname,2)) < 0) {
	perror(fname);
    }
    else {
#ifdef RCJ
	alarm(15);
	while (!access(LOCKFILE,04))
	{
		sleep(1);
	}
	alarm(0);
	close(creat(LOCKFILE,0777));
#else
	fl.l_type = F_WRLCK;
	fl.l_whence = 0;
	fl.l_start = 0;
	fl.l_len = 0L;
	fl.l_pid = getpid ();
	if (fcntl (fd, F_SETLKW, &fl) < 0) {
	    perror(fname);
	}
	else {
#endif
	    do_score(eaten,fd,max_days,type_str);
#ifdef RCJ
	    unlink(LOCKFILE);
#else
	    fl.l_type = F_UNLCK;
	    (void) fcntl (fd, F_SETLK, &fl);
	}
#endif
	(void) close(fd);
    }
    (void) signal(SIGINT,action);
}
-- 

The MAD Programmer -- 919-228-3313 (Cornet 291)
alias: Curtis Jackson	...![ ihnp4 ulysses cbosgd mgnetp ]!burl!rcj
			...![ ihnp4 cbosgd akgua masscomp ]!clyde!rcj