-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpipetty.c
143 lines (126 loc) · 2.94 KB
/
pipetty.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
136
137
138
139
140
141
142
143
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <termios.h>
#include "config.h"
#ifdef HAVE_PTY_H
# include <pty.h>
#endif
#ifdef HAVE_LIBUTIL_H
# include <libutil.h>
#endif
#ifdef HAVE_UTIL_H
# include <util.h>
#endif
extern void sigobit(int ret);
#define PN "pipetty"
void syserr(const char *msg, ...)
{
int err=errno;
va_list ap;
fprintf(stderr, PN ": ");
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
if (err)
fprintf(stderr, ": %s", strerror(err));
fprintf(stderr, "\n");
exit(1);
}
static int basename_is(const char *proc, const char *name)
{
int plen = strlen(proc);
int nlen = strlen(name);
if (plen==nlen && !memcmp(proc, name, nlen))
return 1;
if (plen>nlen && proc[plen-nlen-1]=='/' && !memcmp(proc+plen-nlen, name, nlen))
return 1;
return 0;
}
int main(int argc, const char **argv)
{
if (argc<2)
errno=0, syserr("missing command");
int less = basename_is(argv[0], "lesstty");
struct winsize ws = {};
if (less)
{
if (ioctl(0, TIOCGWINSZ, &ws) && ioctl(1, TIOCGWINSZ, &ws))
ws.ws_row=24, ws.ws_col=80;
}
int master, slave;
if (openpty(&master, &slave, 0, 0/*termios*/, less? &ws : 0))
syserr("can't allocate a pseudo-terminal");
if (master>31)
errno=0, syserr("bad fd from openpty(): %d", master);
struct termios ti;
if (!tcgetattr(slave, &ti))
{
cfmakeraw(&ti);
tcsetattr(slave, TCSANOW, &ti);
}
int pid=fork();
if (pid==-1)
syserr("fork failed");
if (!pid)
{
putenv("PAGER=cat");
close(master);
setsid();
dup2(slave, 1);
dup2(slave, 2);
close(slave);
int zero=0;
ioctl(1, TIOCSCTTY, &zero);
execvp(argv[1], (char*const*)argv+1);
syserr("%s", argv[1]);
return 127;
}
close(slave);
if (less)
{
int p[2];
if (pipe(p))
syserr("pipe failed");
less=fork();
if (less==-1)
syserr("fork failed");
if (!less)
{
close(p[1]);
dup2(p[0], 0);
close(p[0]);
execlp("less", "less", "-R", "-", NULL);
syserr("can't run less");
return 127;
}
close(p[0]);
dup2(p[1], 1);
close(p[1]);
}
char buf[16384];
int r;
while ((r=read(master, buf, sizeof(buf)))>0)
{
if (write(1, buf, r)!=r)
syserr("error writing to stdout");
}
close(master);
int ret;
if (waitpid(pid, &ret, 0)==-1)
syserr("waitpid failed");
if (WIFSIGNALED(ret))
sigobit(ret);
if (less)
{
close(1);
waitpid(less, 0, 0);
}
return WIFEXITED(ret)?WEXITSTATUS(ret):WTERMSIG(ret)+128;
}