1/*++
2/* NAME
3/*	close_on_exec 3
4/* SUMMARY
5/*	set/clear close-on-exec flag
6/* SYNOPSIS
7/*	#include <iostuff.h>
8/*
9/*	int	close_on_exec(int fd, int on)
10/* DESCRIPTION
11/*	the \fIclose_on_exec\fR() function manipulates the close-on-exec
12/*	flag for the specified open file, and returns the old setting.
13/*
14/*	Arguments:
15/* .IP fd
16/*	A file descriptor.
17/* .IP on
18/*	Use CLOSE_ON_EXEC or PASS_ON_EXEC.
19/* DIAGNOSTICS
20/*	All errors are fatal.
21/* LICENSE
22/* .ad
23/* .fi
24/*	The Secure Mailer license must be distributed with this software.
25/* AUTHOR(S)
26/*	Wietse Venema
27/*	IBM T.J. Watson Research
28/*	P.O. Box 704
29/*	Yorktown Heights, NY 10598, USA
30/*--*/
31
32/* System interfaces. */
33
34#include <sys_defs.h>
35#include <fcntl.h>
36
37/* Utility library. */
38
39#include "msg.h"
40
41/* Application-specific. */
42
43#include "iostuff.h"
44
45#define PATTERN	FD_CLOEXEC
46
47/* close_on_exec - set/clear close-on-exec flag */
48
49int     close_on_exec(fd, on)
50int     fd;
51int     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