xref: /original-bsd/usr.bin/nohup/nohup.c (revision ea3a8ee8)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)nohup.c	5.5 (Berkeley) 02/10/93";
16 #endif /* not lint */
17 
18 #include <sys/param.h>
19 #include <sys/stat.h>
20 
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 
29 void dofile __P((void));
30 void usage __P((void));
31 
32 int
33 main(argc, argv)
34 	int argc;
35 	char *argv[];
36 {
37 	if (argc < 2)
38 		usage();
39 
40 	if (isatty(STDOUT_FILENO))
41 		dofile();
42 	if (isatty(STDERR_FILENO) && dup2(STDOUT_FILENO, STDERR_FILENO) == -1) {
43 		/* may have just closed stderr */
44 		(void)fprintf(stdin, "nohup: %s\n", strerror(errno));
45 		exit(1);
46 	}
47 
48 	(void)signal(SIGHUP, SIG_IGN);
49 	(void)signal(SIGQUIT, SIG_IGN);
50 
51 	execvp(argv[1], &argv[1]);
52 	(void)fprintf(stderr,
53 	    "nohup: %s: %s\n", argv[1], strerror(errno));
54 	exit(1);
55 }
56 
57 void
58 dofile()
59 {
60 	int fd;
61 	char *p, path[MAXPATHLEN];
62 
63 #define	FILENAME	"nohup.out"
64 	p = FILENAME;
65 	if ((fd = open(p, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR)) >= 0)
66 		goto dupit;
67 	if (p = getenv("HOME")) {
68 		(void)strcpy(path, p);
69 		(void)strcat(path, "/");
70 		(void)strcat(path, FILENAME);
71 		if ((fd = open(p = path,
72 		    O_RDWR|O_CREAT, S_IRUSR | S_IWUSR)) >= 0)
73 			goto dupit;
74 	}
75 	(void)fprintf(stderr, "nohup: can't open a nohup.out file.\n");
76 	exit(1);
77 
78 dupit:	(void)lseek(fd, (off_t)0, SEEK_END);
79 	if (dup2(fd, STDOUT_FILENO) == -1) {
80 		(void)fprintf(stderr, "nohup: %s\n", strerror(errno));
81 		exit(1);
82 	}
83 	(void)fprintf(stderr, "sending output to %s\n", p);
84 }
85 
86 void
87 usage()
88 {
89 	(void)fprintf(stderr, "usage: nohup command\n");
90 	exit(1);
91 }
92