1、在home下新建shell.c文件,拷贝原有代码,并修改runcmd部分:
void runcmd(struct cmd *cmd)
{
int p[2], r;
struct execcmd *ecmd;
struct pipecmd *pcmd;
struct redircmd *rcmd;
if(cmd == 0)
exit(0);
switch(cmd->type)
{
default:
fprintf(stderr, "unknown runcmd\n");
exit(-1);
case ' ':
ecmd = (struct execcmd*)cmd;
if(ecmd->argv[0] == 0)
exit(0);
// fprintf(stderr, "exec not implemented\n");
// system(ecmd->argv[0]); // Your code here ...
// execl("/bin/sh", "sh", "-c", ecmd->argv[0], (char *)0);
execvp(ecmd->argv[0],ecmd->argv);
break;
case '>':
case '<':
rcmd = (struct redircmd*)cmd;
FILE *stream;
if(rcmd->fd == 1)
stream = freopen(rcmd->file,"w",stdout);
else
freopen(rcmd->file,"r",stdin);
if(stream == NULL)
fprintf(stderr,"errorredirecting\n");
else{
runcmd(rcmd->cmd);
fclose(stream);
}
break;
case '|':
pcmd = (struct pipecmd*)cmd;
int p[2];
if(pipe(p) < 0)
fprintf(stderr,"pipe not implemented\n");
if(pipe(p) == 0){
if(fork1() == 0){
close(1);
dup2(p[1],1);
close(p[0]);
runcmd(pcmd->left);
}
else{
close(0);
dup2(p[0],0);
close(p[1]);
runcmd(pcmd->right);
}
}
// Your code here ...
break;
}
exit(0);
}
2、在home下新建t.sh文件,输入如下代码:
ls > y
cat < y | sort | uniq | wc > y1
cat y1
ls | sort | uniq | wc
rm y
3、运行结果如下图所示: