1 /* $NetBSD: close_on_exec.c,v 1.2 2025/02/25 19:15:51 christos 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(int fd,int on)51 int close_on_exec(int fd, int on)
52 {
53 int flags;
54
55 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
56 msg_fatal("fcntl: get flags: %m");
57 if (fcntl(fd, F_SETFD, on ? flags | PATTERN : flags & ~PATTERN) < 0)
58 msg_fatal("fcntl: set close-on-exec flag %s: %m", on ? "on" : "off");
59 return ((flags & PATTERN) != 0);
60 }
61