Get rid of unnecessary barrier. Improve comment.
[pintos-anon] / src / tests / userprog / shell.c
1 #include <stdbool.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <syscall.h>
5
6 static void read_line (char line[], size_t);
7 static bool backspace (char **pos, char line[]);
8
9 int
10 main (void)
11 {
12   printf ("Shell starting...\n");
13   for (;;) 
14     {
15       char command[80];
16
17       /* Read command. */
18       printf ("--");
19       read_line (command, sizeof command);
20       
21       /* Execute command. */
22       if (!strcmp (command, "exit"))
23         break;
24       else if (command[0] == '\0') 
25         {
26           /* Empty command. */
27         }
28       else
29         {
30           pid_t pid = exec (command);
31           if (pid != PID_ERROR)
32             printf ("\"%s\": exit code %d\n", command, wait (pid));
33           else
34             printf ("exec failed\n");
35         }
36     }
37
38   printf ("Shell exiting.");
39   return 0;
40 }
41
42 /* Reads a line of input from the user into LINE, which has room
43    for SIZE bytes.  Handles backspace and Ctrl+U in the ways
44    expected by Unix users.  On return, LINE will always be
45    null-terminated and will not end in a new-line character. */
46 static void
47 read_line (char line[], size_t size) 
48 {
49   char *pos = line;
50   for (;;)
51     {
52       char c;
53       read (STDIN_FILENO, &c, 1);
54
55       switch (c) 
56         {
57         case '\n':
58           *pos = '\0';
59           putchar ('\n');
60           return;
61
62         case '\b':
63           backspace (&pos, line);
64           break;
65
66         case ('U' - 'A') + 1:       /* Ctrl+U. */
67           while (backspace (&pos, line))
68             continue;
69           break;
70
71         default:
72           /* Add character to line. */
73           if (pos < line + size - 1) 
74             {
75               putchar (c);
76               *pos++ = c;
77             }
78           break;
79         }
80     }
81 }
82
83 /* If *POS is past the beginning of LINE, backs up one character
84    position.  Returns true if successful, false if nothing was
85    done. */
86 static bool
87 backspace (char **pos, char line[]) 
88 {
89   if (*pos > line)
90     {
91       /* Back up cursor, overwrite character, back up
92          again. */
93       printf ("\b \b");
94       (*pos)--;
95       return true;
96     }
97   else
98     return false;
99 }