Remove bb_ prefixes from xfuncs.c (and a few other places), consolidate
[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  * 
9  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10  */
11
12 #include "busybox.h"
13
14 int nohup_main(int argc, char *argv[])
15 {
16         int temp, nullfd;
17         char *nohupout = "nohup.out", *home = NULL;
18
19         // I have no idea why the standard cares about this.
20
21         bb_default_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
28         if (isatty(0)) dup2(nullfd, 0);
29
30         // Redirect stdout to nohup.out, either in "." or in "$HOME".
31
32         if (isatty(1)) {
33                 close(1);
34                 if (open(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR) < 0) {
35                         home = getenv("HOME");
36                         if (home) {
37                                 home = concat_path_file(home, nohupout);
38                                 xopen3(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR);
39                         }
40                 }
41         } else dup2(nullfd, 1);
42
43         // If we have a tty on strderr, announce filename and redirect to stdout.
44         // Else redirect to /dev/null.
45
46         temp = isatty(2);
47         if (temp) fdprintf(2,"Writing to %s\n", home ? home : nohupout);
48         dup2(temp ? 1 : nullfd, 2);
49         close(nullfd);
50         signal (SIGHUP, SIG_IGN);
51
52         // Exec our new program.
53
54         execvp(argv[1],argv+1);
55         if (ENABLE_FEATURE_CLEAN_UP) free(home);
56         bb_error_msg_and_die("exec %s",argv[1]);
57 }