morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base.git
Log | Files | Refs

nohup.c (991B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <errno.h>
      3 #include <fcntl.h>
      4 #include <signal.h>
      5 #include <stdlib.h>
      6 #include <unistd.h>
      7 #include <sys/stat.h>
      8 
      9 #include "util.h"
     10 
     11 enum { Error = 127, Found = 126 };
     12 
     13 static void
     14 usage(void)
     15 {
     16 	eprintf("usage: %s command [argument...]\n", argv0);
     17 }
     18 
     19 int
     20 main(int argc, char *argv[])
     21 {
     22 	int fd;
     23 
     24 	ARGBEGIN {
     25 	default:
     26 		usage();
     27 	} ARGEND;
     28 
     29 	if (argc == 0)
     30 		usage();
     31 
     32 	if (signal(SIGHUP, SIG_IGN) == SIG_ERR)
     33 		enprintf(Error, "signal HUP:");
     34 
     35 	if (isatty(STDOUT_FILENO)) {
     36 		if ((fd = open("nohup.out", O_APPEND|O_CREAT,
     37 			       S_IRUSR|S_IWUSR)) < 0) {
     38 			enprintf(Error, "open nohup.out:");
     39 		}
     40 		if (dup2(fd, STDOUT_FILENO) < 0)
     41 			enprintf(Error, "dup2:");
     42 		close(fd);
     43 	}
     44 	if (isatty(STDERR_FILENO))
     45 		if (dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
     46 			enprintf(Error, "dup2:");
     47 
     48 	execvp(argv[0], &argv[0]);
     49 	enprintf(errno == ENOENT ? Error : Found, "exec %s:", argv[0]);
     50 	_exit(Error);
     51 	/* unreachable */
     52 	return 0;
     53 }