| 12 | #include "vector/vector.h" |
| 13 | |
| 14 | struct hc_proc *_hc_proc_init(struct hc_proc *p, char *cmd[]) { |
| 15 | int fds[2]; |
| 16 | |
| 17 | if (pipe(fds) == -1) { |
| 18 | hc_throw("Failed creating pipe: %d", errno); |
| 19 | } |
| 20 | |
| 21 | pid_t child_pid = fork(); |
| 22 | |
| 23 | switch (child_pid) { |
| 24 | case 0: { |
| 25 | if (close(fds[1]) == -1) { |
| 26 | hc_throw("Failed closing pipe writer: %d", errno); |
| 27 | } |
| 28 | |
| 29 | if (dup2(fds[0], 0) == -1) { |
| 30 | hc_throw("Failed rebinding stdin: %d", errno); |
| 31 | } |
| 32 | |
| 33 | char *const env[] = {"PATH=/bin:/sbin", NULL}; |
| 34 | |
| 35 | if (execve(cmd[0], cmd, env) == -1) { |
| 36 | hc_throw("Failed to execve '%s': %d", cmd[0], errno); |
| 37 | } |
| 38 | } |
| 39 | case -1: |
| 40 | hc_throw("Failed forking process: %d", errno); |
| 41 | default: |
| 42 | if (close(fds[0]) == -1) { |
| 43 | hc_throw("Failed closing pipe reader: %d", errno); |
| 44 | } |
| 45 | |
| 46 | p->pid = child_pid; |
| 47 | p->in = fds[1]; |
| 48 | break; |
| 49 | } |
| 50 | |
| 51 | return p; |
| 52 | } |
| 53 | |
| 54 | static void close_in(struct hc_proc *p) { |
| 55 | if (p->in != -1 && close(p->in) == -1) { |