xref: /illumos-gate/usr/src/lib/libc/port/gen/flock.c (revision b327cd3f3b4dab4f29e7140159b1e01ed2ceef2a)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2015 Joyent, Inc.
14  */
15 
16 #include <sys/feature_tests.h>
17 
18 #include "lint.h"
19 #include <sys/types.h>
20 #include <sys/file.h>
21 #include <unistd.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 
25 int
26 flock(int fildes, int operation)
27 {
28 	struct flock64 l;
29 	int op;
30 	int rv;
31 
32 	l.l_whence = SEEK_SET;
33 	l.l_start = 0;
34 	l.l_len = 0;
35 	l.l_sysid = 0;
36 	l.l_pid = 0;
37 
38 	switch (operation & ~LOCK_NB) {
39 	case LOCK_UN:
40 		if (operation & LOCK_NB) {
41 			errno = EINVAL;
42 			return (-1);
43 		}
44 		l.l_type = F_UNLCK;
45 		rv = fcntl(fildes, F_FLOCK, &l);
46 		break;
47 	case LOCK_EX:
48 	case LOCK_SH:
49 		l.l_type = ((operation & ~LOCK_NB) == LOCK_EX) ?
50 		    F_WRLCK : F_RDLCK;
51 		op = (operation & LOCK_NB) ? F_FLOCK : F_FLOCKW;
52 		rv = fcntl(fildes, op, &l);
53 		break;
54 	default:
55 		errno = EINVAL;
56 		return (-1);
57 	}
58 
59 	return (rv);
60 }
61