1
0

peek(1): handle ^C elegantly

This commit is contained in:
dtb 2024-04-17 14:21:11 -06:00
parent 3ba22dbaf7
commit 6b90e0e1da

View File

@ -1,6 +1,7 @@
#include <signal.h> /* sigaction(2), struct sigaction, SIGINT */
#include <stdio.h> /* fprintf(3), getc(3), perror(3), putc(3), stderr, stdin,
* stdout, EOF, NULL */
#include <stdlib.h> /* size_t */
#include <stdlib.h> /* exit(3), size_t, EXIT_FAILURE */
#include <string.h> /* strerror(3) */
#if !defined EX_OK || !defined EX_OSERR || !defined EX_USAGE
# include <sysexits.h>
@ -12,16 +13,31 @@
static int oserr(char *s){ perror(s); return EX_OSERR; }
static char *program_name = "peek";
static int usage(char *s){
fprintf(stderr, "Usage: %s (-1enot) (-p [program [arguments...]])\n",
s == NULL ? program_name : s);
return EX_USAGE;
}
/* Restores terminal echo; otherwise when a user ^Cs the terminal would
* continue to not display typed text. If sig isn't zero, this will terminate
* the program. */
void restore_echo(int sig){
static struct termios t;
tcgetattr(STDIN_FILENO, &t);
t.c_lflag |= ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &t);
if(sig != 0)
exit(EXIT_FAILURE);
else
return;
}
int main(int argc, char *argv[]){
int c;
int eof;
size_t i;
char include_eof;
FILE *outputs[] = {
NULL /* stdout */,
@ -29,13 +45,15 @@ int main(int argc, char *argv[]){
NULL /* -p */
};
int p[2] = {0, 0};
struct termios t;
if(argc < 1)
usage(argv[0]);
eof = EOF;
include_eof = 0;
{ /* options parsing */
int c;
while((c = getopt(argc, argv, "1enopt")) != -1)
switch(c){
case '1': eof = '\n'; break;
@ -54,6 +72,7 @@ int main(int argc, char *argv[]){
}
default: return usage(argv[0]);
}
}
/* If -p is used there must be additional arguments. getopt(3) wouldn't
* work for this because optarg would have to be one string to give to
@ -75,10 +94,27 @@ int main(int argc, char *argv[]){
return oserr(argv[0]);
}
/* terminal echo */
{ /* install signal handler for ^C to avoid terminal phooeyness */
struct sigaction act = { 0 };
act.sa_handler = restore_echo;
/* This error isn't terminating because the worst that happens is some
* terminal phooeyness if things go awry. */
if(sigaction(SIGINT, &act, NULL) != 0)
perror(argv[0]);
}
{ /* banish terminal echo */
struct termios t;
tcgetattr(STDIN_FILENO, &t);
t.c_lflag ^= ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &t);
}
{ /* actual input loop */
int c;
size_t i;
do{ if((c = getc(stdin)) != eof || include_eof)
for(i = 0; i < (sizeof outputs)/(sizeof *outputs); ++i)
@ -88,10 +124,9 @@ int main(int argc, char *argv[]){
outputs[i] = NULL;
}
}while(c != eof);
}
tcgetattr(STDIN_FILENO, &t);
t.c_lflag |= ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &t);
restore_echo(0);
return EX_OK;
}