From b8f57738b44d9ed8e67d90db72fe89a652f8450d Mon Sep 17 00:00:00 2001 From: Daniel Lezcano Date: Sun, 7 Jun 2009 21:48:46 +0200 Subject: [PATCH] log the container console when it is daemonized and the log is enabled When we daemonize the container and we specify the log file, the container will use the log file to write the console output. Signed-off-by: Daniel Lezcano --- src/lxc/lxc_start.c | 27 ++++++++++++++++++++++++--- src/lxc/start.c | 42 +++++++++++++++++++++++++++++++++++++++--- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/src/lxc/lxc_start.c b/src/lxc/lxc_start.c index b5a34a7b5..9c90771ad 100644 --- a/src/lxc/lxc_start.c +++ b/src/lxc/lxc_start.c @@ -135,9 +135,30 @@ int main(int argc, char *argv[]) my_args.progname, my_args.quiet)) return err; - if (my_args.daemonize && daemon(0 ,0)) { - SYSERROR("failed to daemonize '%s'", my_args.name); - return err; + if (my_args.daemonize) { + + /* do not chdir as we want to open the log file, + * change the directory right after. + * do not close 0, 1, 2, we want to do that + * ourself because we don't want /dev/null + * being reopened. + */ + if (daemon(1 ,1)) { + SYSERROR("failed to daemonize '%s'", my_args.name); + return err; + } + + close(0); + close(1); + close(2); + + if (my_args.log_file) { + open(my_args.log_file, O_WRONLY | O_CLOEXEC); + open(my_args.log_file, O_RDONLY | O_CLOEXEC); + open(my_args.log_file, O_RDONLY | O_CLOEXEC); + } + + chdir("/"); } save_tty(&tios); diff --git a/src/lxc/start.c b/src/lxc/start.c index c3340bb22..0b085604e 100644 --- a/src/lxc/start.c +++ b/src/lxc/start.c @@ -332,6 +332,41 @@ static void remove_init_pid(const char *name, pid_t pid) unlink(init); } +static int fdname(int fd, char *name, size_t size) +{ + char path[MAXPATHLEN]; + + snprintf(path, MAXPATHLEN, "/proc/self/fd/%d", fd); + + return readlink(path, name, size) < 0 ? -1 : 0; +} + +static int console_init(char *console, size_t size) +{ + struct stat stat; + int i; + + for (i = 0; i < 3; i++) { + if (!isatty(i)) + continue; + + if (ttyname_r(i, console, size)) { + SYSERROR("failed to retrieve tty name"); + return -1; + } + return 0; + } + + if (!fstat(0, &stat)) { + if (S_ISREG(stat.st_mode) || S_ISCHR(stat.st_mode) || + S_ISFIFO(stat.st_mode) || S_ISLNK(stat.st_mode)) + return fdname(0, console, size); + } + + console[0] = '\0'; + return 0; +} + int lxc_init(const char *name, struct lxc_handler *handler) { int err = -1; @@ -348,9 +383,10 @@ int lxc_init(const char *name, struct lxc_handler *handler) goto out_put_lock; } - /* If we are not attached to a tty, disable it */ - if (ttyname_r(0, handler->tty, sizeof(handler->tty))) - handler->tty[0] = '\0'; + if (console_init(handler->tty, sizeof(handler->tty))) { + ERROR("failed to initialize the console"); + goto out_aborting; + } if (lxc_create_tty(name, &handler->tty_info)) { ERROR("failed to create the ttys");