This repository has been archived by the owner on Oct 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
sh1.c
133 lines (115 loc) · 2.27 KB
/
sh1.c
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define MAX_BUFFLEN 1024
#define MAX_NUM 100
char *home;
char *dir;
int mysys(const char *cmdstring)
{
pid_t pid;
int status = -1;
if (cmdstring == NULL)
return 1;
if ((pid = fork()) < 0)
status = -1;
else if (pid == 0)
{
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
exit(127);
}
else
{
while (waitpid(pid, &status, 0) < 0)
{
if (errno != EINTR)
{
status = -1;
break;
}
}
}
return status;
}
int judge_buff(char *buff)
{
if(buff[0] == '\0')
return 0;
char code[MAX_BUFFLEN];
strcpy(code, buff);
char *next = strchr(code, ' ');
if(next != NULL)
next[0] = '\0';
//printf("[code] %s", code);
if(strcmp(code, "cd") == 0)
return 1;
else if(strcmp(code, "exit") == 0)
return 2;
else
return 0;
}
int cd(char *buff)
{
char code[MAX_BUFFLEN];
char *argv[MAX_NUM]; // no more than 100 arguments
int count = 0; // N.O. of arguments
char *next = NULL;
char *rest = code;
strcpy(code, buff);
argv[count++] = code;
while(next = strchr(rest, ' '))
{
next[0] = '\0';
rest = next + 1;
// printf("rest = \"%s\"\n", rest);
if(rest[0] != '\0' && rest[0] != ' ')
argv[count++] = rest;
if(count + 2 > MAX_NUM)
return 127;
}
argv[count++] = NULL;
if(count == 2)
{
chdir(home);
dir = getcwd(NULL, 0);
}
else
{
int res = chdir(argv[count - 2]);
dir = getcwd(NULL, 0);
if(res == -1)
{
printf("cd: No such path %s\n", argv[count - 2]);
return -1;
}
}
return 0;
}
int main()
{
home = getenv("HOME");
dir = getcwd(NULL, 0);
char buff[MAX_BUFFLEN];
printf("[%s]$ ", dir);
while(gets(buff))
{
int res = judge_buff(buff);
if(res == 0)
mysys(buff);
else if(res == 1)
cd(buff);
else if(res == 2)
return 0;
printf("[%s]$ ", dir);
}
mysys("pwd");
mysys("echo ,HELLO WORLD , sdfa sdfadf ss ");
mysys("echo /G");
mysys("echo ,,");
mysys("echo");
return 0;
}