Fix build error by adding -fno-stack-protector to CFLAGS in usr/LBuild (#63)
[lunaix-os.git] / lunaix-os / usr / sh / sh.c
index 2ac473a5a6b45839e596e0928a3970cf30eb0d6e..c18b5edc0c435a690e5455bb9b4edf2ee1bce64f 100644 (file)
@@ -1,6 +1,6 @@
 #include <errno.h>
-#include <lunaix/ioctl.h>
-#include <lunaix/lunaix.h>
+#include <sys/ioctl.h>
+#include <sys/wait.h>
 #include <signal.h>
 #include <stdio.h>
 #include <string.h>
@@ -113,6 +113,7 @@ sigint_handle(int signum)
 void
 sh_exec(const char** argv)
 {
+    static int prev_exit;
     const char* envp[] = { 0 };
     char* name = argv[0];
     if (!strcmp(name, "cd")) {
@@ -121,15 +122,48 @@ sh_exec(const char** argv)
         return;
     }
 
+    if (!strcmp(name, "?")) {
+        printf("%d\n", prev_exit);
+        return;
+    }
+
+    char buffer[1024];
+    strcpy(buffer, "/bin/");
+    strcpy(&buffer[5], name);
+
     pid_t p;
+    int res;
     if (!(p = fork())) {
-        if (execve(name, argv, envp)) {
+        if (execve(buffer, argv, envp)) {
             sh_printerr();
         }
         _exit(1);
     }
     setpgid(p, getpgid());
-    waitpid(p, NULL, 0);
+    waitpid(p, &res, 0);
+
+    prev_exit = WEXITSTATUS(res);
+}
+
+static char*
+sanity_filter(char* buf)
+{
+    int off = 0, i = 0;
+    char c;
+    do {
+        c = buf[i];
+        
+        if ((32 <= c && c <= 126) || !c) {
+            buf[i - off] = c;
+        }
+        else {
+            off++;
+        }
+
+        i++;
+    } while(c);
+
+    return buf;
 }
 
 void
@@ -148,7 +182,7 @@ sh_loop()
 
     while (1) {
         getcwd(pwd, 512);
-        printf("[%s]$ ", pwd);
+        printf("%s # ", pwd);
         int sz = read(stdin, buf, 511);
 
         if (sz < 0) {
@@ -157,11 +191,11 @@ sh_loop()
         }
 
         buf[sz] = '\0';
+        sanity_filter(buf);
 
         // currently, this shell only support single argument
         if (!parse_cmdline(buf, argv)) {
-            printf("\n");
-            goto cont;
+             continue;
         }
 
         // cmd=="exit"
@@ -169,9 +203,7 @@ sh_loop()
             break;
         }
 
-        sh_exec((const char**)argv);
-    cont:
-        printf("\n");
+        sh_exec((const char**)argv);       
     }
 }