5

Skeleton of a command processor

  1. /*
  2.  * Skeleton command processor.
  3.  *
  4.  *   select
  5.  *
  6.  *   fgets
  7.  *   fputs
  8.  *   fflush
  9.  *   setbuf
  10.  *   strtok
  11.  *
  12.  *   ONDEBUG
  13.  */
  14.  
  15. #include <sys/select.h>
  16.  
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <strings.h>
  20. #include <errno.h>
  21. #if defined( LINUX )
  22. #include <string.h>
  23. #endif
  24.  
  25. #include "debug.h"
  26.  
  27. #if defined( DEBUG )
  28. int debug = 0;
  29. #endif
  30.  
  31. void prompt() {
  32.     static const char *msg = "? ";
  33.  
  34.     fputs( msg, stdout );
  35. }
  36.  
  37. void startup() {
  38.     prompt();
  39. }
  40.  
  41. void read_input() {
  42.     char line[4096];
  43.     char *tok;
  44.  
  45.     if ( fgets( line, sizeof(line), stdin ) == 0 )
  46.         exit( 0 );
  47.     /* command? */
  48.     if ( (tok = strtok( line, " \t\n" )) ) {
  49.         ONDEBUG( fprintf( stdout, "[%s]\n", tok ); );
  50.         if (tok[0] == 'q' && (tok[1] == '\0' || strcmp(tok, "quit") == 0))
  51.             exit(0);
  52.         if (tok[0] == 'e' && (tok[1] == '\0' || strcmp(tok, "echo") == 0))
  53.             fputs(line + strlen(tok) + 1, stdout);
  54.     }
  55.     prompt();
  56. }
  57.  
  58. void main_loop() {
  59.     fd_set read_fds;
  60.     int n_fds = FD_SETSIZE;
  61.  
  62.     for (;;) { /* forever */
  63.         FD_ZERO(&read_fds);
  64.  
  65.         /* standard input? */
  66.         FD_SET(0, &read_fds);
  67.  
  68.         switch (select(n_fds, &read_fds, 0, 0, 0)) {
  69.         case -1: /* trouble */
  70.             if (errno != EINTR) {
  71.                 fprintf(stderr, "%s\n", strerror(errno));
  72.                 exit( errno);
  73.             }
  74.             break;
  75.         case 0: /* time out */
  76.             break;
  77.         default: /* event */
  78.             if (FD_ISSET(0, &read_fds))
  79.                 read_input(); /* from operator */
  80.             break;
  81.         }
  82.     }
  83. }
  84.  
  85. int main(int argc, char **argv) {
  86.     setbuf(stdout, 0);
  87.  
  88.     startup();
  89.     main_loop();
  90. }

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].