#define LOCK_SH 1
#define LOCK_EX 2
#define LOCK_NB 4
#define LOCK_UN 8

static int
flock(fd, op)
	int fd, op;
{
	struct flock f;

	bzero(&f, sizeof f);
	switch (op & ~LOCK_NB) {
	case LOCK_EX:
		f.l_type = F_WRLCK;
		break;
	case LOCK_SH:
		f.l_type = F_RDLCK;
		break;
	case LOCK_UN:
		f.l_type = F_UNLCK;
		break;
	default:
		errno = EINVAL;
		return -1;
	}
	if (fcntl(fd, (op & LOCK_NB) ? F_SETLK:F_SETLKW, &f) != -1)
		return 0;
	if (errno == EACCES || errno == EAGAIN)
		errno = EWOULDBLOCK;
	return -1;
}
