xref: /original-bsd/usr.bin/nohup/nohup.c (revision 4c3b28fe)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 char copyright[] =
20 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
21  All rights reserved.\n";
22 #endif /* not lint */
23 
24 #ifndef lint
25 static char sccsid[] = "@(#)nohup.c	5.3 (Berkeley) 03/05/90";
26 #endif /* not lint */
27 
28 #include <sys/param.h>
29 #include <sys/signal.h>
30 #include <sys/file.h>
31 #include <unistd.h>
32 #include <stdio.h>
33 
34 extern int errno;
35 
36 main(argc, argv)
37 	int argc;
38 	char **argv;
39 {
40 	char *strerror();
41 
42 	if (argc < 2)
43 		usage();
44 
45 	if (isatty(STDOUT_FILENO))
46 		dofile();
47 	if (isatty(STDERR_FILENO) && dup2(STDOUT_FILENO, STDERR_FILENO) == -1) {
48 		/* may have just closed stderr */
49 		(void)fprintf(stdin, "nohup: %s\n", strerror(errno));
50 		exit(1);
51 	}
52 
53 	(void)signal(SIGHUP, SIG_IGN);
54 	(void)signal(SIGQUIT, SIG_IGN);
55 
56 	execvp(argv[1], &argv[1]);
57 	(void)fprintf(stderr,
58 	    "nohup: %s: %s\n", argv[1], strerror(errno));
59 	exit(1);
60 }
61 
62 dofile()
63 {
64 	int fd;
65 	char *p, path[MAXPATHLEN];
66 	off_t lseek();
67 	char *getenv(), *strcpy(), *strcat(), *strerror();
68 
69 #define	FILENAME	"nohup.out"
70 	p = FILENAME;
71 	if ((fd = open(p, O_RDWR|O_CREAT, 0600)) >= 0)
72 		goto dupit;
73 	if (p = getenv("HOME")) {
74 		(void)strcpy(path, p);
75 		(void)strcat(path, "/");
76 		(void)strcat(path, FILENAME);
77 		if ((fd = open(p = path, O_RDWR|O_CREAT, 0600)) >= 0)
78 			goto dupit;
79 	}
80 	(void)fprintf(stderr, "nohup: can't open a nohup.out file.\n");
81 	exit(1);
82 
83 dupit:	(void)lseek(fd, 0L, SEEK_END);
84 	if (dup2(fd, STDOUT_FILENO) == -1) {
85 		(void)fprintf(stderr, "nohup: %s\n", strerror(errno));
86 		exit(1);
87 	}
88 	(void)fprintf(stderr, "sending output to %s\n", p);
89 }
90 
91 usage()
92 {
93 	(void)fprintf(stderr, "usage: nohup command\n");
94 	exit(1);
95 }
96