*****Listing 2*****

semaphor.c

/* Supported operating systems:  UNIX, MS-DOS */
#define UNIX	(1)
#define MSDOS	(2)
#define HOST	UNIX

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#if HOST == UNIX
#define PATHDLM	('/')	/* path name delimiter */
#include <fcntl.h>	/* open() macro definitions */
#include "syscalkr.h"	/* system call declarations */
#include <sys/stat.h>	/* file mode macros */
#elif HOST == MSDOS
#define PATHDLM	('\\')	/* path name delimiter */
#include <fcntl.h>	/* open() macro definitions */
#include <io.h>		/* close(), open() declarations */
#include <sys/types.h>
#include <sys/stat.h>	/* file mode macros */
#endif
#include "semaphor.h"

/* semaphore set table definition */
static semset_t sst[SEMOPEN_MAX];

/* semlower:  lower semaphore */
int semlower(semset_t *ssp, int semno)
{
	char path[PATH_MAX + 1];

	/* remove semaphore file */
	sprintf(path, "%s%cs%d", ssp->semdir, (int)PATHDLM, semno);
	if (unlink(path) == -1) {
		if (errno == ENOENT) errno = EAGAIN;
		return -1;
	}

	errno = 0;
	return 0;
}

/* semraise:  raise semaphore */
int semraise(semset_t *ssp, int semno)
{
	char path[PATH_MAX + 1];
	int fd = 0;

	/* create semaphore file */
	sprintf(path, "%s%cs%d", ssp->semdir, (int)PATHDLM, semno);
#if HOST == UNIX
	fd = open(path, O_WRONLY | O_CREAT, 0);
#elif HOST == MSDOS
	fd = open(path, O_WRONLY | O_CREAT, S_IREAD | S_IWRITE);
#endif
	if (fd == -1) {
		return -1;
	}
	if (close(fd) == -1) {
		return -1;
	}

	errno = 0;
	return 0;
}

