/*
 * |-----------------------------------------------------------|
 * | Copyright (c) 1991, 1990 MIPS Computer Systems, Inc.      |
 * | All Rights Reserved                                       |
 * |-----------------------------------------------------------|
 * |          Restricted Rights Legend                         |
 * | Use, duplication, or disclosure by the Government is      |
 * | subject to restrictions as set forth in                   |
 * | subparagraph (c)(1)(ii) of the Rights in Technical        |
 * | Data and Computer Software Clause of DFARS 252.227-7013.  |
 * |         MIPS Computer Systems, Inc.                       |
 * |         950 DeGuigne Avenue                               |
 * |         Sunnyvale, California 94088-3650, USA             |
 * |-----------------------------------------------------------|
 */
#ident "$Header: mutexd.c,v 2.3.1.1 92/06/24 13:44:37 marker Exp $"

#include <sys/libmutex.h>

extern mutex_region_type * attach_region ();
extern void (*mutex_wait)();

main (c, v)
char **v;
int c;

{

	char *id = c > 1 ? v[1] : getenv ("MUTEX_ID");

	volatile mutex_region_type *r;
	volatile mutex_proc_type *p;
	mutex_pid_type i, mp, pid; 
	mutex_delay_type sleep;
	mutex_key_type key;
	char *s;
	
	s = getenv ("MUTEXD_TIMEOUT");
	if ((s != (char *)0) && (*s != '\0'))
		sleep = atoi (s);
	else
		sleep = DEFAULT_MUTEXD_TIMEOUT;

	if ((id != (char *)0) && (id != '\0'))
		key = mutex_signature (id);
	else {
		s = getenv ("MUTEX_KEY");
		if ((s != (char *)0) && (*s != '\0'))
			key = atoi (s);
		else
			key = DEFAULT_MUTEX_KEY;
	}

	if ((r = attach_region (key, 0)) == (mutex_region_type *) -1)
		qerror ("mutexd: attach_region failed", 1);

	mp = r->mutex_maxpids;

	while (r->mutex_status) {
		mutex_wait (sleep);
		if (!lock_mutex()) 
			qerror ("mutexd: lock_mutex failed", 2);
		for (i = 1, p = &r->proc[1]; i <= mp; i++, p++)
			if ((p->unix_pid !=0) && is_dead (p->unix_pid)) { 
				deallocate_mutex_pid (i);
		}
		if (r->mutex_procs <= 0) {
			r->mutex_status = 0;
			destroy_mutex();
		}
		else if (!unlock_mutex())
			qerror ("mutexd: unlock_mutex failed", 2);
	}

}
