Imported Upstream version 0.18.1.1
[platform/upstream/gettext.git] / gettext-tools / gnulib-lib / spawn_faction_adddup2.c
1 /* Copyright (C) 2000, 2009, 2010 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 /* Specification.  */
20 #include <spawn.h>
21
22 #include <errno.h>
23 #include <unistd.h>
24
25 #if !_LIBC
26 # define __sysconf(open_max) getdtablesize ()
27 #endif
28
29 #include "spawn_int.h"
30
31 /* Add an action to FILE-ACTIONS which tells the implementation to call
32    `dup2' for the given file descriptors during the `spawn' call.  */
33 int
34 posix_spawn_file_actions_adddup2 (posix_spawn_file_actions_t *file_actions,
35                                   int fd, int newfd)
36 {
37   int maxfd = __sysconf (_SC_OPEN_MAX);
38   struct __spawn_action *rec;
39
40   /* Test for the validity of the file descriptor.  */
41   if (fd < 0 || newfd < 0 || fd >= maxfd || newfd >= maxfd)
42     return EBADF;
43
44   /* Allocate more memory if needed.  */
45   if (file_actions->_used == file_actions->_allocated
46       && __posix_spawn_file_actions_realloc (file_actions) != 0)
47     /* This can only mean we ran out of memory.  */
48     return ENOMEM;
49
50   /* Add the new value.  */
51   rec = &file_actions->_actions[file_actions->_used];
52   rec->tag = spawn_do_dup2;
53   rec->action.dup2_action.fd = fd;
54   rec->action.dup2_action.newfd = newfd;
55
56   /* Account for the new entry.  */
57   ++file_actions->_used;
58
59   return 0;
60 }