Carefully move fd *@from to @to: on success *from set to to */
| 33 | |
| 34 | /* Carefully move fd *@from to @to: on success *from set to to */ |
| 35 | static bool move_fd(int *from, int to) |
| 36 | { |
| 37 | assert(*from >= 0); |
| 38 | |
| 39 | /* dup2 with same arguments may be a no-op, but |
| 40 | * the later close would make the fd invalid. |
| 41 | * Handle this edge case. |
| 42 | */ |
| 43 | if (*from == to) |
| 44 | return true; |
| 45 | |
| 46 | if (dup2(*from, to) == -1) |
| 47 | return false; |
| 48 | |
| 49 | /* dup2 does not duplicate flags, copy it here. |
| 50 | * This should be benign; the only POSIX-defined |
| 51 | * flag is FD_CLOEXEC, and we only use it rarely. |
| 52 | */ |
| 53 | if (fcntl(to, F_SETFD, fcntl(*from, F_GETFD)) < 0) |
| 54 | return false; |
| 55 | |
| 56 | close(*from); |
| 57 | *from = to; |
| 58 | return true; |
| 59 | } |
| 60 | |
| 61 | /* Returns index of fds which is == this fd, or -1 */ |
| 62 | static int fd_used(int **fds, size_t num_fds, int fd) |