-
Notifications
You must be signed in to change notification settings - Fork 5
/
tritty.c
135 lines (109 loc) · 2.36 KB
/
tritty.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/* tritty.c - Copyright (c) 2017, Sijmen J. Mulder (see LICENSE.md) */
#define USAGE "usage: tritty [-b bitrate] [command ...]"
#include <sys/param.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <getopt.h>
#include <signal.h>
#include <string.h>
#include <termios.h>
#include <time.h>
#if defined(__FreeBSD__)
# include <libutil.h>
#elif defined(__APPLE__) || defined(BSD)
# include <util.h>
#else
# include <pty.h>
#endif
#include "trickle.h"
static int fdchild;
static struct termios termios_orig;
static void
onsigwinch(int sig)
{
struct winsize winsize;
(void)sig;
if (!fdchild)
return;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) == -1)
return;
ioctl(fdchild, TIOCSWINSZ, &winsize);
}
static void
restoreterm(void)
{
tcsetattr(STDIN_FILENO, TCSADRAIN, &termios_orig);
}
int
main(int argc, char **argv)
{
char c, *shell;
struct opts opts;
struct winsize winsize;
struct termios termios;
fd_set fdset;
parseopts(argc, argv, &opts);
if (!isatty(STDIN_FILENO) || !isatty(STDIN_FILENO)) {
fputs("not a tty\n", stderr);
return 1;
}
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) == -1) {
perror("TIOCGWINSZ ioctl");
return 1;
}
signal(SIGWINCH, onsigwinch);
switch (forkpty(&fdchild, NULL, NULL, &winsize)) {
case -1:
perror("forkpty");
return 1;
case 0:
if (*opts.argv)
execvp(*opts.argv, opts.argv);
else if ((shell = getenv("SHELL")))
execl(shell, shell, NULL);
else
execl("/bin/sh", "/bin/sh", NULL);
perror("exec");
return 1;
}
if (tcgetattr(STDIN_FILENO, &termios) == -1) {
perror("tcgetattr");
return -1;
}
termios_orig = termios;
atexit(restoreterm);
cfmakeraw(&termios);
if (tcsetattr(STDIN_FILENO, TCSADRAIN, &termios) == -1) {
perror("tcsetattr");
return -1;
}
FD_ZERO(&fdset);
while (1) {
FD_SET(STDIN_FILENO, &fdset);
FD_SET(fdchild, &fdset);
if (select(fdchild+1, &fdset, NULL, NULL, NULL) == -1) {
perror("select");
return 1;
}
if (FD_ISSET(STDIN_FILENO, &fdset)) {
if (read(STDIN_FILENO, &c, 1) != 1)
break;
if (write(fdchild, &c, 1) != 1)
break;
}
if (FD_ISSET(fdchild, &fdset)) {
if (read(fdchild, &c, 1) != 1)
break;
if (write(STDOUT_FILENO, &c, 1) != 1)
break;
}
nanosleep(&opts.delay, NULL);
}
close(fdchild);
return 0;
}