1666f79bfd4153373f50bf8ac951bd199b1a737b
[dana/urxvt.git] / src / test / gettty.c
1 #include "../../config.h"
2
3 #include <stdio.h>
4 #ifdef HAVE_STDLIB_H
5 # include <stdlib.h>
6 #endif
7 #ifdef HAVE_SYS_TYPES_H
8 # include <sys/types.h>
9 #endif
10 #ifdef HAVE_UNISTD_H
11 # include <unistd.h>
12 #endif
13 #include <sys/wait.h>
14
15 int verb = 1;
16
17 int
18 main(int argc)
19 {
20     int             i, pid;
21     int             fd_pty, fd_tty;
22     const char     *ttydev;
23
24     if (argc != 1)
25         verb = 0;
26     fd_pty = fd_tty = -1;
27     ttydev = NULL;
28     fd_pty = rxvt_get_pty(&fd_tty, &ttydev);
29     if (fd_pty < 0) {
30         fprintf(stderr, "rxvt_get_pty() failed\n");
31         exit(1);
32     }
33     if (verb)
34         fprintf(stderr, "rxvt_get_pty() OK.  Found %s (opened pty fd: %d)\n", ttydev, fd_pty);
35
36     if (fd_tty < 0) {
37 # ifdef HAVE_REVOKE
38         revoke(ttydev);
39 # endif
40         if ((fd_tty = rxvt_get_tty(ttydev)) < 0) {
41             fprintf(stderr, "rxvt_get_tty() failed on %s", ttydev);
42             exit(1);
43         }
44         if (verb)
45             fprintf(stderr, "rxvt_get_tty() OK.  (opened tty fd: %d)\n", fd_tty);
46     } else if (verb)
47         fprintf(stderr, "Didn't call: rxvt_get_tty() (already have fd)\n");
48
49     for (i = 0; i < 255; i++)
50         if (i != fd_pty && i != 2 && i != fd_tty)
51             close(i);
52     pid = fork();
53     if (pid) {
54         int             exitst = 1;
55         int             j = 0;
56
57         close(fd_tty);
58         for ( ; ++j < 5; ) {
59             if (waitpid(-1, &i, WNOHANG) != 0)
60                 break;
61             sleep(1);
62         }
63         if (j == 5)
64             kill(pid, 2);
65         if (WIFEXITED(i)) {
66             exitst = WEXITSTATUS(i);
67             if (exitst == 0)
68                 fprintf(stderr, "OK\n");
69             else
70                 fprintf(stderr, "Failed.  Child exit status: %d\n", WEXITSTATUS(i));
71         } else
72             fprintf(stderr, "Interrupted\n");
73         exit(exitst);
74     }
75     close(fd_pty);
76     if (verb)
77         fprintf(stderr, "Calling: rxvt_control_tty\n");
78     i = rxvt_control_tty(fd_tty, ttydev);
79     if (i < 0) {
80         fprintf(stderr, "could not obtain control of tty\n");
81         exit(1);
82     }
83     exit(0);
84     /* NOTREACHED */
85 }