-char *talloc_getcwd(const void *ctx)
-{
- unsigned int len;
- char *cwd;
-
- /* *This* is why people hate C. */
- len = 32;
- cwd = talloc_array(ctx, char, len);
- while (!getcwd(cwd, len)) {
- if (errno != ERANGE) {
- talloc_free(cwd);
- return NULL;
- }
- cwd = talloc_realloc(ctx, cwd, char, len *= 2);
+ if (tools_verbose)
+ printf("Running: %s\n", cmd);
+
+ /* Always flush buffers before fork! */
+ fflush(stdout);
+ start = time_now();
+ pid = fork();
+ if (pid == -1) {
+ close_noerr(p[0]);
+ close_noerr(p[1]);
+ return tal_fmt(ctx, "Failed to fork: %s", strerror(errno));
+ }
+
+ if (pid == 0) {
+ struct itimerval itim;
+
+ if (dup2(p[1], STDOUT_FILENO) != STDOUT_FILENO
+ || dup2(p[1], STDERR_FILENO) != STDERR_FILENO
+ || close(p[0]) != 0
+ || close(STDIN_FILENO) != 0
+ || open("/dev/null", O_RDONLY) != STDIN_FILENO)
+ exit(128);
+
+ signal(SIGALRM, killme);
+ itim.it_interval.tv_sec = itim.it_interval.tv_usec = 0;
+ itim.it_value = timespec_to_timeval(time_from_msec(*timeout_ms));
+ setitimer(ITIMER_REAL, &itim, NULL);
+
+ status = system(cmd);
+ if (WIFEXITED(status))
+ exit(WEXITSTATUS(status));
+ /* Here's a hint... */
+ exit(128 + WTERMSIG(status));
+ }
+
+ close(p[1]);
+ rbuf_init(&in, p[0], tal_arr(ctx, char, 4096), 4096);
+ if (!rbuf_read_str(&in, 0, do_tal_realloc) && errno)
+ in.buf = tal_free(in.buf);
+
+ /* This shouldn't fail... */
+ if (waitpid(pid, &status, 0) != pid)
+ err(1, "Failed to wait for child");
+
+ ms = time_to_msec(time_sub(time_now(), start));
+ if (ms > *timeout_ms)
+ *timeout_ms = 0;
+ else
+ *timeout_ms -= ms;
+ close(p[0]);
+ if (tools_verbose) {
+ printf("%s", in.buf);
+ printf("Finished: %u ms, %s %u\n", ms,
+ WIFEXITED(status) ? "exit status" : "killed by signal",
+ WIFEXITED(status) ? WEXITSTATUS(status)
+ : WTERMSIG(status));