1
0

move peek out of wip

This commit is contained in:
dtb
2023-12-12 20:14:51 -07:00
parent 05bc6b08a8
commit c02b1d4d65
2 changed files with 0 additions and 0 deletions

1
peek/Makefile Normal file
View File

@@ -0,0 +1 @@
peek: peek.c

91
peek/peek.c Normal file
View File

@@ -0,0 +1,91 @@
#include <errno.h> /* errno */
#include <stdio.h> /* fprintf(3), getc(3), putc(3), EOF */
#include <stdlib.h> /* size_t */
#include <string.h> /* strerror(3) */
#if !defined EX_OK || !defined EX_OSERR || !defined EX_USAGE
# include <sysexits.h>
#endif
#include <termios.h> /* tcgetattr(3), tcsetattr(3), struct termios, ECHO */
#include <unistd.h> /* dup(2), execvp(3), fork(2), getopt(3), pipe(2),
* write(2), STDERR_FILENO, STDOUT_FILENO */
static char *program_name = "peek";
int main(int argc, char *argv[]){
int c;
int eof;
size_t i;
char include_eof;
int outputs[] = {0 /* stdout */, 0 /* stderr */, 0 /* -p */};
int p[2] = {0, 0};
struct termios t;
/* terminal echo */
tcgetattr(STDIN_FILENO, &t);
t.c_lflag ^= ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &t);
if(argc < 1)
goto usage;
eof = EOF;
include_eof = 0;
while((c = getopt(argc, argv, "1enop")) != -1)
switch(c){
case '1': eof = '\n'; break;
case 'n': include_eof = 1; break;
case 'o': outputs[0] = STDOUT_FILENO; break;
case 'e': outputs[1] = STDERR_FILENO; break;
case 'p':
if(pipe(p) != 0){
fprintf(stderr, "%s: %s\n",
argv[0], strerror(errno));
return EX_OSERR;
}else
outputs[2] = p[1];
break;
default: goto usage;
}
if((argc > optind && outputs[2] == 0)
|| (!(argc > optind) && outputs[2] != 0)){
usage: fprintf(stderr, "Usage: %s (-1eno)"
" (-p [program [arguments...]])\n",
argv[0] == NULL ? program_name : argv[0]);
return EX_USAGE;
}
if(outputs[2] != 0)
switch(fork()){
case 0:
if(close(p[1]) == 0
&& dup2(p[0], STDIN_FILENO)
== STDIN_FILENO)
execvp(argv[optind], argv + optind);
case -1:
goto die;
default:
if(close(p[0]) != 0)
goto die;
}
do{ if((c = getc(stdin)) != eof || include_eof)
for(i = 0; i < (sizeof outputs)/(sizeof *outputs); ++i)
if(outputs[i] != 0
&& write(outputs[i], &c, 1)
== -1){
if(i == 2)
close(outputs[i]);
outputs[i] = 0;
}
}while(c != eof);
tcgetattr(STDIN_FILENO, &t);
t.c_lflag |= ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &t);
return EX_OK;
die: fprintf(stderr, "%s: %s\n", argv[0], strerror(errno));
return EX_USAGE;
}