]>
diplodocus.org Git - nmh/blob - test/runpty.c
e5de14e0c05f31aaa774de75f20e569154347c86
2 * runpty.c - Run a process under a pseudo-tty
4 * This code is Copyright (c) 2017, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
15 #include <sys/types.h>
17 #include <sys/select.h>
21 #define COMMAND_TIMEOUT 30
24 main(int argc
, char *argv
[])
26 int master
, slave
, cc
, sendeof
= 0, status
;
28 const char *slavename
;
30 unsigned char readbuf
[1024];
34 fprintf(stderr
, "Usage: %s output-filename command [arguments ...]\n",
39 if ((master
= posix_openpt(O_RDWR
| O_NOCTTY
)) < 0) {
40 fprintf(stderr
, "Unable to open master pseudo-tty: %s\n",
45 if (grantpt(master
) < 0) {
46 fprintf(stderr
, "Unable to grant permissions to master pty: %s\n",
51 if (unlockpt(master
) < 0) {
52 fprintf(stderr
, "Unable to unlock master pty: %s\n", strerror(errno
));
56 if (!(slavename
= ptsname(master
))) {
57 fprintf(stderr
, "Unable to determine name of slave pty: %s\n",
62 if ((slave
= open(slavename
, O_RDWR
| O_NOCTTY
)) < 0) {
63 fprintf(stderr
, "Unable to open slave pty \"%s\": %s\n", slavename
,
71 * Start the child process if we are in the child; close the master
72 * as we are supposed to only use the slave ptys here.
77 dup2(slave
, STDIN_FILENO
);
78 dup2(slave
, STDOUT_FILENO
);
79 dup2(slave
, STDERR_FILENO
);
82 execvp(argv
[2], argv
+ 2);
84 fprintf(stderr
, "execvp(%s) failed: %s\n", argv
[2], strerror(errno
));
85 } else if (child
< 0) {
86 fprintf(stderr
, "fork() failed: %s\n", strerror(errno
));
92 if (!(output
= fopen(argv
[1], "w"))) {
93 fprintf(stderr
, "Unable to open \"%s\" for output: %s\n", argv
[1],
98 starttime
= time(NULL
);
106 FD_SET(master
, &readfds
);
109 * Okay, what's going on here?
111 * We want to send the EOF character (to simulate a "end of file",
112 * as if we redirected stdin to /dev/null). We can't just close
113 * master, because we won't be able to get any data back. So,
114 * after we get SOME data, set sendeof, and that will cause us to
115 * send the EOF character after the first select call. If we are
116 * doing sendeof, set the timeout to 1 second; otherwise, set the
117 * timeout to COMMAND_TIMEOUT seconds remaining.
123 tv
.tv_sec
= starttime
+ COMMAND_TIMEOUT
- time(NULL
);
129 cc
= select(master
+ 1, &readfds
, NULL
, NULL
, &tv
);
132 fprintf(stderr
, "select() failed: %s\n", strerror(errno
));
136 if (cc
> 0 && FD_ISSET(master
, &readfds
)) {
137 cc
= read(master
, readbuf
, sizeof(readbuf
));
142 fwrite(readbuf
, 1, cc
, output
);
145 if (cc
== 0 && sendeof
) {
148 if (tcgetattr(master
, &rtty
) < 0) {
149 fprintf(stderr
, "tcgetattr() failed: %s\n", strerror(errno
));
153 if (rtty
.c_lflag
& ICANON
)
154 write(master
, &rtty
.c_cc
[VEOF
], 1);
158 if (time(NULL
) > starttime
+ COMMAND_TIMEOUT
) {
159 fprintf(stderr
, "Command execution timed out\n");
167 waitpid(child
, &status
, 0);