summaryrefslogtreecommitdiff
path: root/sh.c
blob: 9e0cb3f73bca2b2c93f1d1ca2ddcfa025c75ee15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fs.h"
#include "fcntl.h"

char *args[100];
void parse(char buf[]);

int
main(void)
{
  char buf[128];
  int pid;

  while(1){
    puts("$ ");
    memset (buf, '\0', sizeof(buf));
    gets(buf, sizeof(buf));
    if(buf[0] == '\0')
      continue;
    pid = fork();
    if(pid == 0){
      parse(buf);
      if (buf[0] == 'c' && buf[1] == 'd' && buf[2] == '\0') {  // cd
	chdir(&buf[3]);
      } else {
	exec(buf, args);
	printf(1, "%s: not found\n", buf);
	exit();
      }
    }
    if(pid > 0)
      wait();
  }
}

void
parse(char buf[])
{
  int j = 1;
  int i;
  args[0] = buf;
  for (i = 0; buf[i] != '\0'; i++) {
    if (buf[i] == ' ') {
      buf[i] = '\0';
      args[j++] = buf + i + 1;
      if (j >= 100) {
	printf(2, "too many args\n");
	exit();
      }
    }
  }
  args[j] = '\0';
}