EXEC_PREFER_APPLETS support by Gabriel L. Somlo <somlo@cmu.edu>
[platform/upstream/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 int nohup_main(int argc, char **argv)
17 {
18         int nullfd;
19         const char *nohupout;
20         char *home = NULL;
21
22         xfunc_error_retval = 127;
23
24         if (argc < 2) bb_show_usage();
25
26         nullfd = xopen(bb_dev_null, O_WRONLY|O_APPEND);
27         /* If stdin is a tty, detach from it. */
28         if (isatty(STDIN_FILENO))
29                 dup2(nullfd, STDIN_FILENO);
30
31         nohupout = "nohup.out";
32         /* Redirect stdout to nohup.out, either in "." or in "$HOME". */
33         if (isatty(STDOUT_FILENO)) {
34                 close(STDOUT_FILENO);
35                 if (open(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR) < 0) {
36                         home = getenv("HOME");
37                         if (home) {
38                                 nohupout = concat_path_file(home, nohupout);
39                                 xopen3(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR);
40                         }
41                 }
42         } else dup2(nullfd, STDOUT_FILENO);
43
44         /* If we have a tty on stderr, announce filename and redirect to stdout.
45          * Else redirect to /dev/null.
46          */
47         if (isatty(STDERR_FILENO)) {
48                 bb_error_msg("appending to %s", nohupout);
49                 dup2(STDOUT_FILENO, STDERR_FILENO);
50         } else dup2(nullfd, STDERR_FILENO);
51
52         if (nullfd > 2)
53                 close(nullfd);
54         signal(SIGHUP, SIG_IGN);
55
56         BB_EXECVP(argv[1], argv+1);
57         if (ENABLE_FEATURE_CLEAN_UP && home)
58                 free((char*)nohupout);
59         bb_perror_msg_and_die("%s", argv[1]);
60 }