]>
diplodocus.org Git - nmh/blob - test/runpty.c
ef5cf822f0da6932dd55401ee2e7dd542342fb6a
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.
16 #include <sys/types.h>
18 #include <sys/select.h>
22 #define COMMAND_TIMEOUT 30
24 static int open_master_pty(const char *desc
);
25 static void die(const char *fmt
, ...);
28 main(int argc
, char *argv
[])
30 int master_in
, master_out
, slave
, cc
, status
;
31 time_t starttime
, now
;
32 const char *slavename
;
34 unsigned char readbuf
[1024];
38 die("%s: too few arguments\n"
39 "usage: %s output-filename command [arguments...]\n",
43 master_in
= open_master_pty("input");
44 master_out
= open_master_pty("output");
49 * Start the child process if we are in the child; open the two
50 * slave pseudo-ttys and close the masters after we are done with them.
54 if (!(slavename
= ptsname(master_in
))) {
55 die("Unable to determine name of slave pty: %s\n",
59 if ((slave
= open(slavename
, O_RDWR
)) < 0) {
60 die("Unable to open slave pty \"%s\": %s\n", slavename
,
64 dup2(slave
, STDIN_FILENO
);
68 if (!(slavename
= ptsname(master_out
))) {
69 die("Unable to determine name of slave pty: %s\n",
73 if ((slave
= open(slavename
, O_RDWR
| O_NOCTTY
)) < 0) {
74 die("Unable to open slave pty \"%s\": %s\n", slavename
,
78 dup2(slave
, STDOUT_FILENO
);
79 dup2(slave
, STDERR_FILENO
);
83 execvp(argv
[2], argv
+ 2);
85 die("execvp(%s) failed: %s\n", argv
[2], strerror(errno
));
87 } else if (child
< 0) {
88 die("fork() failed: %s\n", strerror(errno
));
91 if (!(output
= fopen(argv
[1], "w"))) {
92 die("Unable to open \"%s\" for output: %s\n", argv
[1],
96 starttime
= time(NULL
);
104 FD_SET(master_out
, &readfds
);
107 * After we get our first bit of data, close the master pty
108 * connected to standard input on our slave; that will generate
112 tv
.tv_sec
= starttime
+ COMMAND_TIMEOUT
- time(NULL
);
117 cc
= select(master_out
+ 1, &readfds
, NULL
, NULL
, &tv
);
120 die("select() failed: %s\n", strerror(errno
));
123 if (cc
> 0 && FD_ISSET(master_out
, &readfds
)) {
124 cc
= read(master_out
, readbuf
, sizeof(readbuf
));
129 fwrite(readbuf
, 1, cc
, output
);
131 if (master_in
!= -1) {
138 if (now
>= starttime
+ COMMAND_TIMEOUT
) {
139 fprintf(stderr
, "Command execution timed out: %ld to %ld: %d\n",
150 waitpid(child
, &status
, 0);
156 open_master_pty(const char *desc
)
160 if ((fd
= posix_openpt(O_RDWR
| O_NOCTTY
)) == -1) {
161 die("Unable to open master %s pseudo-tty: %s\n", desc
, strerror(errno
));
163 if (grantpt(fd
) == -1) {
164 die("Unable to grant permissions to master %s pty: %s\n", desc
,
167 if (unlockpt(fd
) == -1) {
168 die("Unable to unlock master %s pty: %s\n", desc
, strerror(errno
));
175 die(const char *fmt
, ...)
180 vfprintf(stderr
, fmt
, args
);