use bb_sanitize_stdio() where appropriate
[oweals/busybox.git] / coreutils / nohup.c
1 /* vi: set sw=4 ts=4: */
2 /* nohup - invoke a utility immune to hangups.
3  *
4  * Busybox version based on nohup specification at
5  * http://www.opengroup.org/onlinepubs/007904975/utilities/nohup.html
6  *
7  * Copyright 2006 Rob Landley <rob@landley.net>
8  * Copyright 2006 Bernhard Fischer
9  *
10  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
11  */
12
13 #include "busybox.h"
14
15 int nohup_main(int argc, char **argv)
16 {
17         int nullfd;
18         const char *nohupout;
19         char *home = NULL;
20
21         xfunc_error_retval = 127;
22
23         if (argc < 2) bb_show_usage();
24
25         nullfd = xopen(bb_dev_null, O_WRONLY|O_APPEND);
26         /* If stdin is a tty, detach from it. */
27         if (isatty(STDIN_FILENO))
28                 dup2(nullfd, STDIN_FILENO);
29
30         nohupout = "nohup.out";
31         /* Redirect stdout to nohup.out, either in "." or in "$HOME". */
32         if (isatty(STDOUT_FILENO)) {
33                 close(STDOUT_FILENO);
34                 if (open(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR) < 0) {
35                         home = getenv("HOME");
36                         if (home) {
37                                 nohupout = concat_path_file(home, nohupout);
38                                 xopen3(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR);
39                         }
40                 }
41         } else dup2(nullfd, STDOUT_FILENO);
42
43         /* If we have a tty on stderr, announce filename and redirect to stdout.
44          * Else redirect to /dev/null.
45          */
46         if (isatty(STDERR_FILENO)) {
47                 bb_error_msg("appending to %s", nohupout);
48                 dup2(STDOUT_FILENO, STDERR_FILENO);
49         } else dup2(nullfd, STDERR_FILENO);
50
51         if (nullfd > 2)
52                 close(nullfd);
53         signal(SIGHUP, SIG_IGN);
54
55         execvp(argv[1], argv+1);
56         if (ENABLE_FEATURE_CLEAN_UP && home)
57                 free((char*)nohupout);
58         bb_perror_msg_and_die("%s", argv[1]);
59 }