+/* Return if file descriptor is opened. */
+static inline int
+fd_is_valid (int fd)
+{
+ return fcntl_not_cancel_2 (fd, F_GETFD) != -1 || errno != EBADF;
+}
+
/* Function used in the clone call to setup the signals mask, posix_spawn
attributes, and file actions. It run on its own stack (provided by the
posix_spawn call). */
@@ -219,6 +226,15 @@ __spawni_child (void *arguments)
case spawn_do_open:
{
+ /* POSIX states that if fildes was already an open file descriptor,
+ it shall be closed before the new file is opened. This avoid
+ pontential issues when posix_spawn plus addopen action is called
+ with the process already at maximum number of file descriptor
+ opened and also for multiple actions on single-open special
+ paths (like /dev/watchdog). */
+ if (fd_is_valid (action->action.open_action.fd))
+ close_not_cancel (action->action.open_action.fd);