scroll

scrollbackbuffer program for st
git clone git://git.suckless.org/scroll
Log | Files | Refs | README

commit 6010f1f28817ad49ed50eca2a0b3a8a90126fd95
parent 4c4aa0e7eb7df99f1bcad885432141dc1cf43dc7
Author: Jan Klemkow <j.klemkow@wemelug.de>
Date:   Wed, 15 Apr 2020 22:07:56 +0200

ptty: add event loop to handle input and output for future tests

Diffstat:
Mptty.c | 39+++++++++++++++++++++++++++++++++------
1 file changed, 33 insertions(+), 6 deletions(-)

diff --git a/ptty.c b/ptty.c @@ -3,6 +3,7 @@ #include <errno.h> #include <inttypes.h> #include <limits.h> +#include <poll.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> @@ -88,16 +89,42 @@ main(int argc, char *argv[]) } /* parent */ - FILE *fh = fdopen(mfd, "rw"); - if (fh == NULL) - die("fdopen"); if (closeflag && close(mfd) == -1) die("close:"); - char buf[BUFSIZ]; - while (fgets(buf, sizeof buf, fh) != NULL) - fputs(buf, stdout); + struct pollfd pfd[2] = { + { STDIN_FILENO, POLLIN, 0}, + { mfd, POLLIN, 0} + }; + + for (;;) { + char buf[BUFSIZ]; + ssize_t n; + int r; + + if ((r = poll(pfd, 2, -1)) == -1) + die("poll:"); + + if (pfd[0].revents & POLLIN) { + if ((n = read(STDIN_FILENO, buf, sizeof buf)) == -1) + die("read:"); + if (n == 0) break; + if (write(mfd, buf, n) == -1) + die("write:"); + } + + if (pfd[1].revents & POLLIN) { + if ((n = read(mfd, buf, sizeof buf)) == -1) + die("read:"); + if (n == 0) break; + if (write(STDOUT_FILENO, buf, n) == -1) + die("write:"); + } + + if (pfd[0].revents & POLLHUP || pfd[1].revents & POLLHUP) + break; + } int status; waitpid(pid, &status, 0);