-
Notifications
You must be signed in to change notification settings - Fork 0
/
pty.c
121 lines (93 loc) · 2.84 KB
/
pty.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
#include "apue.h"
static void set_noecho(int); /* at the end of this file */
void do_driver(char *); /* in the file driver.c */
void loop(int, int); /* in the file loop.c */
void reap(int signum){
wait(NULL);
}
#define MAXLEN 100
pid_t forker(int *ptrfdm, char *slave_name, char *argv[]);
int main(int argc, char *argv[]) {
int fdm;
if(argv[1][0] == '@'){
//reaper
signal(SIGCHLD, reap);
unlink(argv[2]);
mkfifo(argv[2], 0666);
int fd = open(argv[2], O_RDWR);
FILE* fp = fdopen(fd, "rw");
if (fp == NULL) {
perror("Failed: ");
return 1;
}
char buffer[MAXLEN];
while(1){
if (fgets(buffer, MAXLEN - 1, fp)){
printf("PTY: %s", buffer);
buffer[strcspn(buffer, "\n")] = 0;
pid_t pid = forker(&fdm, buffer, argv+1);
if( pid == 0){
exit(0);
}
}
}
}else{
char *slave_name = argv[1];
pid_t pid = forker(&fdm, slave_name, argv);
if( pid > 0){
waitpid(pid, NULL, 0);
}
}
}
int
ptys_open (char *pts_name)
{
int fds;
//TODO restore solaris support
if ((fds = open (pts_name, O_RDWR)) < 0)
return (-1);
return (fds);
}
static void set_noecho(int fd) /* turn off echo (for slave pty) */
{
struct termios stermios;
if (tcgetattr(fd, &stermios) < 0)
err_sys("tcgetattr error");
stermios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
/*
* Also turn off NL to CR/NL mapping on output.
*/
stermios.c_oflag &= ~(ONLCR);
if (tcsetattr(fd, TCSANOW, &stermios) < 0)
err_sys("tcsetattr error");
}
pid_t forker(int *ptrfdm, char *slave_name, char *argv[]){
pid_t pid = fork();
if( ! pid ){
int fds;
if (setsid() < 0)
err_sys("setsid error");
/*
* System V acquires controlling terminal on open().
*/
if ((fds = ptys_open(slave_name)) < 0)
err_sys("can't open slave pty");
//TODO restore bsd support
/*
* Slave becomes stdin/stdout/stderr of child.
*/
if (dup2(fds, STDIN_FILENO) != STDIN_FILENO)
err_sys("dup2 error to stdin");
if (dup2(fds, STDOUT_FILENO) != STDOUT_FILENO)
err_sys("dup2 error to stdout");
if (dup2(fds, STDERR_FILENO) != STDERR_FILENO)
err_sys("dup2 error to stderr");
if (fds != STDIN_FILENO && fds != STDOUT_FILENO && fds != STDERR_FILENO)
close(fds);
//set_noecho(STDIN_FILENO); /* stdin is slave pty */
if (execvp(argv[2], &argv[2]) < 0)
err_sys("can't execute: %s", argv[2]);
return (0); /* child returns 0 just like fork() */
}
return pid;
}