在Linux Ubuntu 20.04.4中,我在;sh.c"文件进入
./a.out
命令逐行正常运行。在此处输入图像描述
ls > y
cat < y | sort | uniq | wc > y1
cat y1
rm y1
ls | sort | uniq | wc
rm y
但是,如果将命令保存到";t.sh";文件在此处输入图像描述并像一样立即运行它们
./a.out < t.sh
出现错误。在此处输入图像描述
打印结果:
5 5 29
5 5 29
cat: y1: No such file or directory
rm: Cannot erase 'y1': no such file or directory
4 4 27
rm: Cannot clear 'y': no such file or directory
当我用";ls〃;命令,cat和rm命令都运行良好,但我收到了这样的错误消息"rm:无法擦除"y1":没有这样的文件或目录">
怎么了?另一个人使用相同的代码正常工作。。。
这是实现的代码的一部分。
void runcmd(struct cmd *cmd)
{
int p[2], r;
int fd;
int pid;
char str[30] ="/bin/";
FILE * stream;
struct execcmd *ecmd;
struct pipecmd *pcmd;
struct redircmd *rcmd;
if(cmd == 0)
_exit(0);
switch(cmd->type){
default:
fprintf(stderr, "unknown runcmdn");
_exit(-1);
case ' ':
ecmd = (struct execcmd*)cmd;
if(ecmd->argv[0] == 0){
_exit(0);
fprintf(stderr, "exec not implementedn");
}
// Your code here ...
else if(execvp(ecmd->argv[0],ecmd->argv)==-1){
ecmd->argv[0] = strcat(str,ecmd->argv[0]);
if(execvp(ecmd->argv[0],ecmd->argv)==-1){
fprintf(stderr,"file not foundn");
exit(1);
}
}
break;
case '>':
rcmd = (struct redircmd*)cmd;
ecmd = (struct execcmd*)(rcmd->cmd);
if(0 <(fd = open(rcmd->file,O_CREAT|O_WRONLY,0644))){
stream = freopen(rcmd->file,"w",stdout);
runcmd(rcmd->cmd);
fclose(stream);
}
else {
fprintf(stderr,"file open errorn");
}
close(fd);
stream = NULL;
break;
case '<':
rcmd = (struct redircmd*)cmd;
// Your code here ...
if( 0 < (fd = open(rcmd->file,rcmd->flags))){
stream = freopen(rcmd->file,"r",stdin);
runcmd(rcmd->cmd);
fclose(stream);
close(fd);
}
else fprintf(stderr,"file open errorn");
break;
case '|':
pcmd = (struct pipecmd*)cmd;
// Your code here ...
struct cmd * lcmd =(pcmd->left);
struct cmd * rcmd =(pcmd->right);
int fd[2];
if(pipe(fd)==-1){
fprintf(stderr,"pipe error");
exit(1);
}
pid = fork1();
if(pid == 0){
dup2(fd[1],1);
close(fd[0]);
runcmd(lcmd);
}
else{
dup2(fd[0],0);
close(fd[1]);
runcmd(rcmd);
}
break;
}
_exit(0);
}
您已声明#/脚本顶部的bin.sh