
/*
 * NOTTY.C - program to disconnect a program from the tty and close
 *           stdin, stdout, and stderr (-012 to specify which descriptors
 *           to leave open).
 *
 * (c)Copyright 1994, Matthew Dillon, All rights reserved.  This code may
 *    be used in any project, commercial or otherwise, as long as I am given
 *    appropriate credit and as long as this copyright remains intact in all
 *    source and document files.
 *
 * NOTTY [-012] <command>
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/wait.h>

main(ac, av)
char *av[];
{
    char *opts = "";
    int ttyfd;

    if (av[1]) {
    	if (av[1][0] == '-') {
    	    opts = av[1];
    	    ++av;
	}
    }


    ttyfd = open("/dev/null", O_RDWR);

    if (strchr(opts, '0') == NULL && ttyfd != 0)
    	dup2(ttyfd, 0);
    if (strchr(opts, '1') == NULL && ttyfd != 1)
    	dup2(ttyfd, 1);
    if (strchr(opts, '2') == NULL && ttyfd != 2)
    	dup2(ttyfd, 2);

    if (ttyfd > 2)
    	close(ttyfd);

    {
	int fd = open("/dev/tty", O_RDWR);
	if (fd >= 0) {
	    ioctl(fd, TIOCNOTTY, 0);
	    close(fd);
	} 
    }

/*  signal(SIGCHLD, SIG_IGN); */
    if (fork() == 0) {
    	setpgrp();
	exit(execvp(av[1], av + 1));
    }
    exit(0);
}

