实现myshell 的重定向实际上就是进程间的程序替换
由于要替换的ls程序是在/usr/bin目录下的ls程序
因此可以直接使用带p的exec函数,由于我们需要从标准输入中读数据,并且将这些命令参数解释出来用此我们需要一个指针数组来保存这些输入的命令参数
因此我们需要使用execvp函数
如果我们需要实现myshell的重定向,我们需要改变输出的重定向,那么我们需要改变文件描述符所指向的内容。
#include<stdio.h>
#include<iostream>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
using namespace std;
int main()
{
printf("[admin@localhost linux_myshell]#");
fflush(stdout);
char buf[1024];
ssize_t ret= read(0,buf,(sizeof(buf))-1);
if(ret>0)
{
buf[ret-1]=0;
printf("buf: %s\n",buf);
}
// char _argv
char *_argv[32];
char *start=buf;
char *file=NULL;
bool flag=false;
bool cTag=false;
_argv[0]=buf;
int i=1;
while(*start)
{
if(*start==' ')
{
*start=0;
start++;
if(*start=='>')
{
start++;
if(*start=='>')
{
flag=true;
start++;
}
file=start;
cTag=true;
break;
}
else
{
_argv[i++]=start;
}
}
else
{
start++;
}
}
_argv[i]=NULL;
pid_t id=fork();
if(id==0)
{
printf("child start\n");
if(cTag)
{
close(1);
if(flag)
{
int ret=open(file, O_WRONLY|O_CREAT|O_APPEND,0644);
execvp(_argv[0],_argv);
close(ret);
}
else
{
int ret=open(file, O_WRONLY|O_CREAT,0644);
ftruncate(ret,0);
execvp(_argv[0],_argv);
close(ret);
}
}
else
{
execvp(_argv[0],_argv);
}//一定要注意否则就会因为关闭了文件描述符使普通的ls -a -l显示不出来
}
else
{
pid_t ret=wait(NULL);
if(ret)
{
printf("wait success!\n");
}
}
return 0;
}