forked from Percona-QA/percona-qa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpty.c
79 lines (67 loc) · 1.82 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
#define _XOPEN_SOURCE 600
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
int main (int argc, char * const argv[]) {
int masterfd, slavefd;
char *slavedevice;
int child_pid, child_retval;
char line[BUFSIZ];
if (argc < 2) {
fprintf(stderr, "Usage: ./pty <program> [<arg>*]\n");
return 0;
}
masterfd = posix_openpt(O_RDWR|O_NOCTTY);
if (masterfd == -1
|| grantpt(masterfd) == -1
|| unlockpt(masterfd) == -1
|| (slavedevice = ptsname(masterfd)) == NULL) {
fprintf(stderr, "Unable to open pty.\n");
return -1;
}
if ((child_pid = fork()) == -1) {
fprintf(stderr, "Unable to fork.\n");
return -1;
}
if (child_pid) {
FILE *masterfp;
/* open master end of pty and unbuffer stdout */
setvbuf(stdout, (char *) NULL, _IONBF, 0);
masterfp = fdopen(masterfd, "r");
while (fgets(line, BUFSIZ, masterfp) != NULL) {
/* convert ending \r\n to \n */
int i;
for (i = 0; line[i]; i++) {
if (line[i] == '\r' && line[i+1] == '\n' && line[i+2] == '\0') {
line[i] = '\n';
line[i+1] = '\0';
}
}
fputs(line, stdout);
}
wait(&child_retval);
if (child_retval) {
fprintf(stdout, "\nProgram terminated with exit code %d.\n", child_retval);
}
return child_retval;
} else {
/* open slave end of pty */
slavefd = open(slavedevice, O_RDWR|O_NOCTTY);
if (slavefd < 0) {
fprintf(stderr, "Unable to open slave end.\n");
return -1;
}
dup2(slavefd, 1); /* replace stdout with slave end of pty */
close(masterfd);
close(slavefd);
execvp(argv[1], &argv[1]);
/* if execv returns, then it failed to execute the program */
perror("Failed to execute program");
return -1;
}
return 0;
}