-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMyshell(linux).txt
More file actions
68 lines (65 loc) · 1.51 KB
/
Myshell(linux).txt
File metadata and controls
68 lines (65 loc) · 1.51 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
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
int main()
{
while(1)
{
printf("[myshell@myhostname test]# ");
fflush(stdout);
char buf[1024];
ssize_t s= read(0,buf,sizeof(buf)-1);//[*]
if(s>0)
{
buf[s-1]=0;
}
char* argv[32];
char* start = buf;
argv[0]=buf;
int i = 1;
while(*start)
{
if(*start==' ')
{
*start=0;
start++;
argv[i++]=start;
}
else
start++;
}
argv[i]=NULL;
if(strcmp(argv[i-2],">") == 0)// ">" exp: ls>Makefile
{
argv[i-2] = NULL;
pid_t id = fork();
if(id == 0)
{//child
close(1);
open(argv[i-2],O_WRONLY|O_CREAT,0666);
int ret = execvp(argv[0],argv);
if(ret == 0)
perror("execerror!");
exit(1);
}
}
pid_t id = fork();
if(id==0)
{//child
int ret = execvp(argv[0],argv);
if(ret==0)
perror("execerror!");
exit(1);
}
else
{//father
wait(NULL);
}
}
return 0;
}