xref: /illumos-gate/usr/src/lib/libc/port/sys/lockf.c (revision 8119dad84d6416f13557b0ba8e2aaf9064cbcfd3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1988 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 #include <sys/feature_tests.h>
31 
32 #if !defined(_LP64) && _FILE_OFFSET_BITS == 64
33 #define	__lockf		__lockf64
34 #endif
35 
36 #include "lint.h"
37 #include <sys/types.h>
38 #include <unistd.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 
42 int
43 __lockf(int fildes, int function, off_t size)
44 {
45 	struct flock l;
46 	int rv;
47 
48 	l.l_whence = 1;
49 	if (size < 0) {
50 		l.l_start = size;
51 		l.l_len = -size;
52 	} else {
53 		l.l_start = (off_t)0;
54 		l.l_len = size;
55 	}
56 	switch (function) {
57 	case F_ULOCK:
58 		l.l_type = F_UNLCK;
59 		rv = fcntl(fildes, F_SETLK, &l);
60 		break;
61 	case F_LOCK:
62 		l.l_type = F_WRLCK;
63 		rv = fcntl(fildes, F_SETLKW, &l);
64 		break;
65 	case F_TLOCK:
66 		l.l_type = F_WRLCK;
67 		rv = fcntl(fildes, F_SETLK, &l);
68 		break;
69 	case F_TEST:
70 		l.l_type = F_WRLCK;
71 		rv = fcntl(fildes, F_GETLK, &l);
72 		if (rv != -1) {
73 			if (l.l_type == F_UNLCK)
74 				return (0);
75 			else {
76 				errno = EAGAIN;
77 				return (-1);
78 			}
79 		}
80 		break;
81 	default:
82 		errno = EINVAL;
83 		return (-1);
84 	}
85 	if (rv < 0) {
86 		switch (errno) {
87 		case EMFILE:
88 		case ENOSPC:
89 		case ENOLCK:
90 			/*
91 			 * A deadlock error is given if we run out of resources,
92 			 * in compliance with /usr/group standards.
93 			 */
94 			errno = EDEADLK;
95 			break;
96 		default:
97 			break;
98 		}
99 	}
100 	return (rv);
101 }
102