1 #include<stdio.h>
2 #include<unistd.h>
3 #include<string.h>
4 #include<sys/wait.h>
5 #include<stdlib.h>
6 #include<sys/types.h>
7 #include<fcntl.h>
8 #include<sys/stat.h>
9 #include<pwd.h>
10 void GetPwd()
11 {
12 char pwd[256]={0};
13 getcwd(pwd,sizeof(pwd)-1);//pwd存储的为相对路径
14 int len=strlen(pwd);
15 //用p获取当前路径
16 char* p=pwd+len;
17 while(*p!='/'&&len--)
18 --p;
19 ++p;
20 printf(" %s]#",p);
21 }
22 void GetLoginname()
23 {
24 struct passwd *pwd=getpwuid(getuid());
25 printf("[%s",pwd->pw_name);
26 }
27
28 void GetHostname()
29 {
30 char name[256]={0};
31 int ret=gethostname(name,256);
32 if(ret==0)
33 printf("@%s",name);
34 }
35 int main() {
36 while(1){
37 // printf("[myshell@myhostNameMaHua test]#");
38 GetLoginname();
39 GetHostname();
40 GetPwd();
41 fflush(stdout);
42 char buf[1024];
43 ssize_t s=read(0,buf,sizeof(buf)-1);
44 if(s>0) {
45 buf[ s-1 ]=0;
46 printf("%s\n",buf);
47
48 }
49 char *_argv[32];
50 _argv[0] = buf;
51 int i =0;
52 char *start = buf;
53 while(*start) {
54 if(*start ==' ') {
55 *start = 0;
56 start++;
57 _argv[i++] = start;
58 }
59 else {
60 start++;
61 }
62 }
63 _argv[i] = NULL;
64 pid_t id = fork();
65 if(id < 0) {
66 printf("creat process fail!\n");
67 exit(-1);
68 }
69 if(id==0) {//child
70 int j=0;
71 int fd;
72 for(j=0;j<=i;j++)
73 {
74 if(strcmp(_argv[j],">")==0) //输出重定向
75 {
76 char* file=_argv[j+1];
77 _argv[j]=NULL;
78 close(1); //关闭标准输出显示器 文件描述符1
79 fd=open(file,O_WRONLY|O_CREAT|O_TRUNC,0666);
80 }
81 }
82 execvp(_argv[0], _argv);
83 exit(1);
84 }
85 else {
86 //father
87 int status = 0;
88 pid_t ret = waitpid(id, &status, 0);
89 if( ret >0) {
90 if(WIFEXITED(status))
91 {
92 printf("exitCode: %d\n",WEXITSTATUS(status));
93 }
94 else
95 {
96 printf("child quit by sig!\n");
97 }
98 }
99 }
100 }
101 return 0;
102 }
[wgp@localhost shell]$ ls -l -a -i -n > 2.c
