00001 #include <stdbool.h>
00002
00003 #include <stdio.h>
00004 #include <string.h>
00005 #include <syscall.h>
00006
00007 static void read_line (char line[], size_t);
00008 static bool backspace (char **pos, char line[]);
00009
00010 int
00011 main (void)
00012 {
00013 printf ("Shell starting...\n");
00014 for (;;)
00015 {
00016 char command[80];
00017
00018
00019 printf ("--");
00020 read_line (command, sizeof command);
00021
00022
00023 if (!strcmp (command, "exit"))
00024 break;
00025 else if (!memcmp (command, "cd ", 3))
00026 {
00027 if (!chdir (command + 3))
00028 printf ("\"%s\": chdir failed\n", command + 3);
00029 }
00030 else if (command[0] == '\0')
00031 {
00032
00033 }
00034 else
00035 {
00036 pid_t pid = exec (command);
00037 if (pid != PID_ERROR)
00038 printf ("\"%s\": exit code %d\n", command, wait (pid));
00039 else
00040 printf ("exec failed\n");
00041 }
00042 }
00043
00044 printf ("Shell exiting.");
00045 return EXIT_SUCCESS;
00046 }
00047
00048
00049
00050
00051
00052 static void
00053 read_line (char line[], size_t size)
00054 {
00055 char *pos = line;
00056 for (;;)
00057 {
00058 char c;
00059 read (STDIN_FILENO, &c, 1);
00060
00061 switch (c)
00062 {
00063 case '\r':
00064 *pos = '\0';
00065 putchar ('\n');
00066 return;
00067
00068 case '\b':
00069 backspace (&pos, line);
00070 break;
00071
00072 case ('U' - 'A') + 1:
00073 while (backspace (&pos, line))
00074 continue;
00075 break;
00076
00077 default:
00078
00079 if (pos < line + size - 1)
00080 {
00081 putchar (c);
00082 *pos++ = c;
00083 }
00084 break;
00085 }
00086 }
00087 }
00088
00089
00090
00091
00092 static bool
00093 backspace (char **pos, char line[])
00094 {
00095 if (*pos > line)
00096 {
00097
00098
00099 printf ("\b \b");
00100 (*pos)--;
00101 return true;
00102 }
00103 else
00104 return false;
00105 }