-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmy_shell_test.c
More file actions
68 lines (61 loc) · 1.21 KB
/
my_shell_test.c
File metadata and controls
68 lines (61 loc) · 1.21 KB
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
/*****************************
* 思路
* **************************/
//1.获取命令行
//2.解析命令行
//3.建立一个子进程(fork)
//4.替换子进程(execvp)
//5.父进程等待子进程的退出
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<ctype.h>
#include<unistd.h>
//全局变量
int argc = 0;
char *argv[8];
//分析函数
void do_parse(char *buf){
int i;
int status = 0;
for(i=argc=0;buf[i];i++){
if(status == 0 && !(isspace(buf[i]))){
argv[argc++] = buf + i;
status = 1;
}else if(isspace(buf[i])){
buf[i] = 0;
status = 0;
}
}
argv[argc] == NULL;
}
//执行函数
void do_execute(void){
pid_t pid = fork();
if(pid == -1){
perror("fork");
exit(1);
}
if(pid == 0){
execvp(argv[0],argv);
perror("execvp");
exit(EXIT_FAILURE);
}else{
int st;
while(wait(&st) != pid){
;
}
}
}
int main(){
char buf[1024] = {};
while(1){
printf("myshell>");
scanf("%[^\n]%*c",buf);
do_parse(buf);
do_execute();
}
return 0;
}