/*-=-=-=-=-=-=-=-=-=-=-=- RCCL/RCI Notice of Copyright -=-=-=-=-=-=-=-=-=-=-*
 *									    *
 *	Copyright (C) 1987, 1991 by John E. Lloyd.			    *
 *									    *
 *	Information on copyright permissions, as well as a complete	    *
 *	disclaimer of warranty, is given in the file COPYRIGHT.		    *
 *									    *
 *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

/*---------------------------------------------------------------------------
 *		
 * MODULE NAME:	lockRobot
 *
 * DESCRIPTION:	Routine to make sure that the same robot cannot be
 *		connected to by two RCI tasks (or programs) at once.
 *
 * AUTHOR/DATE:	John Lloyd, Fall 1987
 *
 * MODIFICATION HISTORY:
 *
 *--------------------------------------------------------------------------*/

#include <sys/file.h>
#include <errno.h>

extern int errno;

#include "../h/cdefs.h"
#include "../h/errorCodes.h"

/* ----- Error Messages. Defined externally to save space ----- */

static char *noRCCLEnvMsg	= "%s -- environment variable RCCL not set\n";
static char *cantOpenFileMsg	= "%s -- can't open file %s\n";
static char *cantFlockFileMsg	= "%s -- can't flock file %s\n";

lockRobot (name)
char *name;
{
	/* Lock connection access to the named robot */

#ifndef VXWORKS_CFG		/* XXX */

#define FNS	256
	char fileName[FNS];	
	char *rcclDir;
	int fd;

	char *fxnName = "lockRobot()";

	if ((rcclDir = (char *)getenvRCCL()) == NULL)
	 { errorMsg (EEnviron, noRCCLEnvMsg, fxnName);
	   return (-1);
	 }
	sprintf (fileName, "%s/lock/%s", rcclDir, name);

	if ((fd = open (fileName, O_CREAT | O_WRONLY, 0666)) < 0)
	 { errorMsg (EBadAccess, cantOpenFileMsg, fxnName, fileName);
	   return (-1);
	 }
	fchmod (fd, 0666);

	if (flock (fd, LOCK_NB | LOCK_EX) < 0)
	 { if (errno == EWOULDBLOCK)
	    { return (0);
	    }
	   else
	    { errorMsg (EBadAccess, cantFlockFileMsg, fxnName,fileName,errno);
	      return (-1);
	    }
	 }
#endif
	return (1);	   
}
