| 45 | |
| 46 | extern "C" |
| 47 | FILE * popen(const char *command, const char *mode) |
| 48 | { |
| 49 | FILE *fp; |
| 50 | int parent_fd, child_fd; |
| 51 | int pipe_fds[2]; |
| 52 | pid_t child_pid; |
| 53 | char new_mode[2] = "r"; |
| 54 | |
| 55 | int do_read = 0; |
| 56 | int do_write = 0; |
| 57 | int do_cloexec = 0; |
| 58 | |
| 59 | while (*mode != '\0') { |
| 60 | switch (*mode++) { |
| 61 | case 'r': |
| 62 | do_read = 1; |
| 63 | break; |
| 64 | case 'w': |
| 65 | do_write = 1; |
| 66 | break; |
| 67 | case 'e': |
| 68 | do_cloexec = 1; |
| 69 | break; |
| 70 | default: |
| 71 | errno = EINVAL; |
| 72 | return NULL; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | if ((do_read ^ do_write) == 0) { |
| 77 | errno = EINVAL; |
| 78 | return NULL; |
| 79 | } |
| 80 | |
| 81 | { |
| 82 | WrapperLock disableCheckpoint; |
| 83 | if (pipe(pipe_fds) < 0) { |
| 84 | return NULL; |
| 85 | } |
| 86 | |
| 87 | // Mark the parent_end with FD_CLOEXEC so that if there is fork/exec while |
| 88 | // we are inside this wrapper, these fds are closed. |
| 89 | fcntl(pipe_fds[0], F_SETFD, FD_CLOEXEC); |
| 90 | fcntl(pipe_fds[1], F_SETFD, FD_CLOEXEC); |
| 91 | |
| 92 | if (do_read) { |
| 93 | parent_fd = pipe_fds[0]; |
| 94 | child_fd = pipe_fds[1]; |
| 95 | strcpy(new_mode, "r"); |
| 96 | } else { |
| 97 | parent_fd = pipe_fds[1]; |
| 98 | child_fd = pipe_fds[0]; |
| 99 | strcpy(new_mode, "w"); |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | child_pid = fork(); |
| 104 | if (child_pid == 0) { |