实现一个minishell(经验+3 ↑)
shell?
命令行解释器(本质就是一个程序) ,功能是将用户所要进行的操作传递给内核。
shell的实现
首先我们需要知道命令行开头的内容是啥 。
为了区别系统的shell,我将自己写的用户名改为“ljl1 ”;
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/wait.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
while(1)
{
char buf[1024] = {0};
printf("[ljl1@VM-0-5-centos Shell]$ ");
fflush(stdout);//手动刷新缓冲区
fgets(buf,1023,stdin);//从标准输入中读取1023个字节到buf中,留一个字节放\0
buf[strlen(buf)-1] = '\0';
char *str = buf;
int redirect_flag = 0;//1-清空 ,2-追加重定向;
char *redirect_file = NULL;
while(*str != '\0')
{
if(*str == '>')
{
redirect_flag = 1;
*str = '\0';
str++;
if(*str == '>')
{
redirect_flag = 2;
str++;
}
while(*str != '\0' && *str == ' ')
str++;
redirect_file = str;
while(*str != '\0' && *str != ' ')
str++;
*str = '\0';
}
str++;
}
char *ptr = buf;
char myargv[32][32] = {{0}};
int myargc = 0;
while(*ptr != '\0')
{
if(!isspace(*ptr))
{
int count = 0;
while(!isspace(*ptr) && *ptr != '\0')
{
myargv[myargc][count] = *ptr;
count++;
ptr++;
}
myargc++;
}
ptr++;
}
char* arg[32] = {NULL};
int i = 0;
for(i = 0;i<myargc;++i)
{
arg[i] = myargv[i];
}
arg[myargc] = NULL;
pid_t pid = fork();
if(pid < 0)
continue;
else if(pid == 0)
{
if(redirect_flag == 1)
{
int fd = open(redirect_file, O_CREAT|O_TRUNC|O_WRONLY,0664);
dup2(fd,1);
}
else if(redirect_flag == 2)
{
int fd = open(redirect_file,O_CREAT|O_APPEND|O_WRONLY,0664);
dup2(fd,1);
}
execvp(arg[0],arg);
exit(-1);
}
wait(NULL);
}
return 0;
}
走起~
完成。
本文版权归去快排Seo www.SEOgurublog.com 所有,如有转发请注明来出,竞价开户托管,seo优化请联系QQ▷61910465