From 0982ad2613d4ace40c5d14b0815f1285eac69451 Mon Sep 17 00:00:00 2001 From: Sargun Dhillon Date: Wed, 12 Apr 2017 02:27:36 -0700 Subject: [PATCH] Add FD swap / redirect stderr code --- src/tini.c | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/tini.c b/src/tini.c index a0d6328..5d8c42b 100644 --- a/src/tini.c +++ b/src/tini.c @@ -136,8 +136,29 @@ int isolate_child() { int spawn(const signal_configuration_t* const sigconf_ptr, char* const argv[], int* const child_pid_ptr) { + int new_stdout_fd = 1; + int new_stderr_fd = 2; + char *redir_path; pid_t pid; + redir_path = getenv("REDIR_STDOUT"); + if (redir_path) { + new_stdout_fd = open(redir_path, O_WRONLY | O_CREAT | O_APPEND); + if (new_stdout_fd == -1) { + PRINT_FATAL("Failed to open stdout redirect path: %s", strerror(errno)); + return 1; + } + } + + redir_path = getenv("REDIR_STDERR"); + if (redir_path) { + new_stderr_fd = open(redir_path, O_WRONLY | O_CREAT | O_APPEND); + if (new_stderr_fd == -1) { + PRINT_FATAL("Failed to open stderr redirect path: %s", strerror(errno)); + return 1; + } + } + // TODO: check if tini was a foreground process to begin with (it's not OK to "steal" the foreground!") pid = fork(); @@ -156,6 +177,17 @@ int spawn(const signal_configuration_t* const sigconf_ptr, char* const argv[], i return 1; } + // Do the FD swap + // No need to set CLO_EXEC on existing stdout, stderr FDs, because we're closing them anyway + if (dup2(new_stdout_fd, 1) == -1) { + PRINT_FATAL("Failed to duplicate stdout FD: %s", strerror(errno)); + return 1; + } + if (dup2(new_stderr_fd, 2) == -1) { + PRINT_FATAL("Failed to duplicate stdout FD: %s", strerror(errno)); + return 1; + } + execvp(argv[0], argv); // execvp will only return on an error so make sure that we check the errno