1/* Adjust a file descriptor result so that it avoids clobbering
2 STD{IN,OUT,ERR}_FILENO, with specific flags.
3
4 Copyright (C) 2005-2006, 2009-2019 Free Software Foundation, Inc.
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18
19/* Written by Paul Eggert and Eric Blake. */
20
21#include <config.h>
22
23/* Specification. */
24#include "unistd-safer.h"
25
26#include <errno.h>
27#include <unistd.h>
28
29/* Return FD, unless FD would be a copy of standard input, output, or
30 error; in that case, return a duplicate of FD, closing FD. If FLAG
31 contains O_CLOEXEC, the returned FD will have close-on-exec
32 semantics. On failure to duplicate, close FD, set errno, and
33 return -1. Preserve errno if FD is negative, so that the caller
34 can always inspect errno when the returned value is negative.
35
36 This function is usefully wrapped around functions that return file
37 descriptors, e.g., fd_safer_flag (open ("file", O_RDONLY | flag), flag). */
38
39int
40fd_safer_flag (int fd, int flag)
41{
42 if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
43 {
44 int f = dup_safer_flag (fd, flag);
45 int e = errno;
46 close (fd);
47 errno = e;
48 fd = f;
49 }
50
51 return fd;
52}
53