/*
 * libnqs/comms/daepres.c
 * 
 * DESCRIPTION:
 *
 *	Determine if the local NQS daemon is present.
 *
 *	Original Author:
 *	-------
 *	Brent A. Kingsbury, Sterling Software Incorporated.
 *	October 3, 1985.
 */


#include <libnqs/license.h>			/* NQS definitions */
#include <libnqs/defines.h>
#include <libnqs/proto.h>

#if	HAS_BSD_PIPE
#include <sys/file.h>
#else
#include <libnqs/nqspacket.h>			/* NQS local message packets */
#endif
#include <libnqs/transactcc.h>			/* TCMx_ codes */

/*** daepres
 *
 *
 *	int daepres():
 *	Determine if the local NQS daemon is present.
 *
 *	Returns:
 *		1: if the local NQS daemon IS present.
 *		0: if the local NQS daemon is NOT present.
 */
#if	HAS_BSD_PIPE
int daepres (struct confd *runfile) 	/* Locked exclusively if the NQS */
					/* daemon is running just fine; */
					/* Unlocked if NQS is not running, */
					/* or is shutting down */
{
  	assert(runfile != NULL);
  
	if (flock (runfile->fd, LOCK_SH | LOCK_NB) == -1) {
		/*
		 *  The local NQS daemon has the queues file locked
		 *  exclusively with an advisory lock, and is therefore
		 *  running.
		 */
		return (1);		/* Local NQS daemon is running */
	}
	/*
	 *  We were able to successfully apply a shared advisory lock to
	 *  the queues file.  Therefore, the local NQS daemon is either
	 *  shutdown, or in the process of shutting down.
	 *
	 *  Before we return, we must give up the shared advisory lock,
	 *  so that a future incarnation of the resurrected NQS daemon, can
	 *  successfully apply an advisory exclusive lock on the queues
	 *  file.
	 */
	flock (runfile->fd, LOCK_UN);	/* Release the lock */
	return (0);			/* Local NQS daemon is not running */
}
#else
int daepres (void)
{
	interclear();
	if (inter (PKT_SENSEDAEMON) == TCML_COMPLETE) return (1);
	return (0);			/* The NQS daemon is not running */
}
#endif
