xref: /netbsd-src/external/ibm-public/postfix/dist/src/util/close_on_exec.c (revision 41fbaed053f8fbfdf9d2a4ee0a7386a3c83f8505)
1 /*	$NetBSD: close_on_exec.c,v 1.1.1.1 2009/06/23 10:08:59 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	close_on_exec 3
6 /* SUMMARY
7 /*	set/clear close-on-exec flag
8 /* SYNOPSIS
9 /*	#include <iostuff.h>
10 /*
11 /*	int	close_on_exec(int fd, int on)
12 /* DESCRIPTION
13 /*	the \fIclose_on_exec\fR() function manipulates the close-on-exec
14 /*	flag for the specified open file, and returns the old setting.
15 /*
16 /*	Arguments:
17 /* .IP fd
18 /*	A file descriptor.
19 /* .IP on
20 /*	Use CLOSE_ON_EXEC or PASS_ON_EXEC.
21 /* DIAGNOSTICS
22 /*	All errors are fatal.
23 /* LICENSE
24 /* .ad
25 /* .fi
26 /*	The Secure Mailer license must be distributed with this software.
27 /* AUTHOR(S)
28 /*	Wietse Venema
29 /*	IBM T.J. Watson Research
30 /*	P.O. Box 704
31 /*	Yorktown Heights, NY 10598, USA
32 /*--*/
33 
34 /* System interfaces. */
35 
36 #include <sys_defs.h>
37 #include <fcntl.h>
38 
39 /* Utility library. */
40 
41 #include "msg.h"
42 
43 /* Application-specific. */
44 
45 #include "iostuff.h"
46 
47 #define PATTERN	FD_CLOEXEC
48 
49 /* close_on_exec - set/clear close-on-exec flag */
50 
close_on_exec(fd,on)51 int     close_on_exec(fd, on)
52 int     fd;
53 int     on;
54 {
55     int     flags;
56 
57     if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
58 	msg_fatal("fcntl: get flags: %m");
59     if (fcntl(fd, F_SETFD, on ? flags | PATTERN : flags & ~PATTERN) < 0)
60 	msg_fatal("fcntl: set close-on-exec flag %s: %m", on ? "on" : "off");
61     return ((flags & PATTERN) != 0);
62 }
63