/*
** @(#) Revision 1.1 - 01/17/97
** semutils.c
**
** ======================================================================= 
** Andrea Whitlock, Mobius Software Services
** whitlock@mobius-soft.com
** 
** Bug reports, questions, and suggestions should be emailed to:
** mobius@mobius-soft.com
**
** This software is provided under the terms of the GNU copyleft
** (ftp://prep.ai.mit.edu/pub/gnu/COPYING-2.0), without a warranty
** of any kind.  Use at your own risk.
** ======================================================================= 
**
** Description:
** Semaphore utility functions.
**
** Notes:
** Set tabstops to 4.
**
*/

#include "semutils.h"

static char semutilsSccsId[] = "@(#)semutils.c	1.1\t01/17/97";
static char semutilsVerId[] = "VER 1.1";

void
set_sembuf_struct(struct sembuf *s, int num, int op, int flg)
{
	s->sem_num = (short) num;
	s->sem_op = op;
	s->sem_flg = flg;
	return;
}

int
remove_semaphore(int semid)
{
	return semctl(semid, 0, IPC_RMID, 0);
}

int
initialize_semaphore(int semid, int val)
{
	return semctl(semid, 0, SETVAL, val);
	return semctl(semid, 0, SETVAL, val);
}

int
make_semaphore(int *semid, char *logfile, char keyid)
{
	key_t			logkey;
	char			message[255];

	/* create the semaphore key */

	if ((logkey = ftok(logfile, keyid)) == (key_t) -1) {
		sprintf(message, "could not derive key from filename %s id %c",
			logfile, keyid);
		perror(message);
		return 1;
	} 

	/* return handle to existing semaphore */

	if ((*semid = semget(logkey, SETSIZE, PERMS)) < 0) {

		/* create new semaphore */

		if ((*semid = semget(logkey, SETSIZE, PERMS | IPC_CREAT)) < 0) {
			if (errno != EEXIST) {
				sprintf(message, "could not create semaphore with key %d", 
					(int)logkey);
			} else {
				sprintf(message, "could not access semaphore with key %d",
					(int)logkey);
			}
			perror(message);
			return 1;
		} 

		/* initialize new semaphore */

		if (initialize_semaphore(*semid, 1) == -1) {
			perror("could not initialize semaphore");
			exit(1);
		}
	}

	return 0;
}

