5
Skeleton of a command processor
- /*
- * Skeleton command processor.
- *
- * select
- *
- * fgets
- * fputs
- * fflush
- * setbuf
- * strtok
- *
- * ONDEBUG
- */
- #include <sys/select.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <strings.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- #include "debug.h"
- #if defined( DEBUG )
- int debug = 0;
- #endif
- void prompt() {
- static const char *msg = "? ";
- fputs( msg, stdout );
- }
- void startup() {
- prompt();
- }
- void read_input() {
- char line[4096];
- char *tok;
- if ( fgets( line, sizeof(line), stdin ) == 0 )
- exit( 0 );
- /* command? */
- if ( (tok = strtok( line, " \t\n" )) ) {
- ONDEBUG( fprintf( stdout, "[%s]\n", tok ); );
- if (tok[0] == 'q' && (tok[1] == '\0' || strcmp(tok, "quit") == 0))
- exit(0);
- if (tok[0] == 'e' && (tok[1] == '\0' || strcmp(tok, "echo") == 0))
- fputs(line + strlen(tok) + 1, stdout);
- }
- prompt();
- }
- void main_loop() {
- fd_set read_fds;
- int n_fds = FD_SETSIZE;
- for (;;) { /* forever */
- FD_ZERO(&read_fds);
- /* standard input? */
- FD_SET(0, &read_fds);
- switch (select(n_fds, &read_fds, 0, 0, 0)) {
- case -1: /* trouble */
- if (errno != EINTR) {
- fprintf(stderr, "%s\n", strerror(errno));
- exit( errno);
- }
- break;
- case 0: /* time out */
- break;
- default: /* event */
- if (FD_ISSET(0, &read_fds))
- read_input(); /* from operator */
- break;
- }
- }
- }
- int main(int argc, char **argv) {
- setbuf(stdout, 0);
- startup();
- main_loop();
- }
Comments