xref: /titanic_41/usr/src/lib/libc/port/gen/truncate.c (revision f52e84dfce89ba2ea0ebb6a191b4466da3012efd)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*	Copyright (c) 1988 AT&T	*/
30 /*	  All Rights Reserved  	*/
31 
32 
33 /*
34  * ftruncate() and truncate() set a file to a specified
35  * length using fcntl(F_FREESP) system call. If the file
36  * was previously longer than length, the bytes past the
37  * length will no longer be accessible. If it was shorter,
38  * bytes not written will be zero filled.
39  */
40 
41 #include <sys/feature_tests.h>
42 
43 #if !defined(_LP64) && _FILE_OFFSET_BITS == 64
44 #pragma weak ftruncate64 = _ftruncate64
45 #pragma weak truncate64 = _truncate64
46 #define	_ftruncate	_ftruncate64
47 #define	_truncate	_truncate64
48 #else /* !_LP64 && _FILE_OFFSET_BITS == 64 */
49 #pragma weak ftruncate = _ftruncate
50 #pragma weak truncate = _truncate
51 #endif /* !_LP64 && _FILE_OFFSET_BITS == 64 */
52 
53 #include "synonyms.h"
54 #include <unistd.h>
55 #include <stdio.h>
56 #include <fcntl.h>
57 #include <pthread.h>
58 #include <sys/types.h>
59 
60 int
61 _ftruncate(int fildes, off_t len)
62 {
63 	struct flock lck;
64 
65 	lck.l_whence = 0;	/* offset l_start from beginning of file */
66 	lck.l_start = len;
67 	lck.l_type = F_WRLCK;	/* setting a write lock */
68 	lck.l_len = (off_t)0;	/* until the end of the file address space */
69 
70 	if (fcntl(fildes, F_FREESP, &lck) == -1) {
71 		return (-1);
72 	}
73 	return (0);
74 }
75 
76 int
77 _truncate(const char *path, off_t len)
78 {
79 
80 	int rval = 0;
81 	int cancel_state;
82 	int fd;
83 
84 	/*
85 	 * truncate() is not a cancellation point,
86 	 * even though it calls open() and close().
87 	 */
88 	(void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_state);
89 	if ((fd = open(path, O_WRONLY)) == -1 || ftruncate(fd, len) == -1)
90 		rval = -1;
91 	if (fd >= 0)
92 		(void) close(fd);
93 	(void) pthread_setcancelstate(cancel_state, NULL);
94 	return (rval);
95 }
96