- sh1.c: 实现shell程序,要求具备如下功能
- 支持命令参数
$ echo arg1 arg2 arg3
$ ls /bin /usr/bin /home
- 实现内置命令cd、pwd、exit
$ cd /bin
$ pwd
/bin
实现思路:在获取命令字符串后,用strtok函数对字符串进行处理,获取参数列表,然后判断命令是内部命令还是外部命令,进行分别处理。
1、内部命令的实现:内部命令全部自己实现,exit
通过myexit()
函数实现,myexit()
直接调用exit(0)
,cd
通过mycd()
函数调用chdir()
函数来实现,pwd
通过mypwd()
函数调用getcdw()
函数实现。
2、外部命令的实现:外部命令通过在cmd函数中创建子进程,在子进程通过execvp()
函数装载外部命令实现。
实现代码:
#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<string.h>
#include<pwd.h>#define MAX_PATH_LEN 200
#define CMD_LEN 200
int cmd_num;
char *cmd_array[100];void cmd(){pid_t pid;pid=fork();if(pid==0){if(execvp(cmd_array[0],cmd_array)<0){printf("Error:command not found\n");}}wait(NULL);
}void print_user(){struct passwd *pwd;char path_name[MAX_PATH_LEN];getcwd(path_name,MAX_PATH_LEN);pwd=getpwuid(getuid());printf("%s@kali:%s$ ",pwd->pw_name,path_name);
}void get_cmd(){int i=0;char str[CMD_LEN];char *buf;cmd_num=0;memset(cmd_array,0,100);fgets(str,CMD_LEN,stdin);buf=strtok(str," \n");while(buf!=NULL){cmd_array[i]=(char *)malloc(sizeof(*buf));strcpy(cmd_array[i++],buf);buf=strtok(NULL," \n");}cmd_array[i]=NULL;cmd_num=i;
}void mycd(){struct passwd *pwd;char path_name[MAX_PATH_LEN];pwd=getpwuid(getuid());if(cmd_num==1){strcpy(path_name,pwd->pw_dir);if(chdir(path_name)==-1){perror("mycd:chdir..");exit(1);}}else{if(chdir(cmd_array[1])==-1){printf("mycd: cd:%s:No such directory\n",cmd_array[1]);}}
}void myexit(){exit(0);
}void mypwd(){char path_name[MAX_PATH_LEN];if(getcwd(path_name,MAX_PATH_LEN)){printf("%s\n",path_name);}else{perror("Error:getcwd...\n");exit(0);}
}int main(){while(1){print_user();get_cmd();if(cmd_array[0]==NULL)return 0;else if(strcmp(cmd_array[0],"exit")==0)myexit();else if(strcmp(cmd_array[0],"pwd")==0)mypwd();else if(strcmp(cmd_array[0],"cd")==0)mycd();else cmd();}return 0;
}
运行结果
欢迎留言交流。。。。