acmecert: Fix cryptography bugs.
[utils.git] / notty.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <sys/ioctl.h>
6
7 void usage(void)
8 {
9     fprintf(stderr, "usage: notty PROGRAM [-r] [ARGS...]\n");
10 }
11
12 int main(int argc, char **argv)
13 {
14     int tty, retain;
15     int c;
16     
17     retain = 0;
18     while((c = getopt(argc, argv, "r")) >= 0) {
19         switch(c) {
20         case 'r':
21             retain = 1;
22             break;
23         case '?':
24         case ':':
25         default:
26             usage();
27             exit(1);
28         }
29     }
30     if(argc - optind < 1) {
31         usage();
32         exit(1);
33     }
34     if((tty = open("/dev/tty", O_RDWR)) < 0) {
35         perror("/dev/tty");
36         exit(1);
37     }
38     if(ioctl(tty, TIOCNOTTY)) {
39         perror("TIOCNOTTY");
40         exit(1);
41     }
42     if(retain) {
43         if(tty != 3) {
44             dup2(tty, 3);
45             close(tty);
46         }
47     } else {
48         close(tty);
49     }
50     execvp(argv[optind], argv + optind);
51     perror(argv[optind]);
52     return(127);
53 }