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