【发布时间】:2018-10-23 00:16:14
【问题描述】:
我一直在编写自定义 shell 脚本,并在使用下面给出的代码重定向输出时遇到了一个小错误。在其当前状态下,代码运行良好,但在传递给 execvp args 时会引发错误,例如:(ls ">" no such file or directory)。我知道这是因为它将整个 args[] 传递给不起作用的父 shell。添加 args[j] = NULL 会删除 "" 从而修复错误,但也会导致重定向不再起作用。我怎样才能让它不抛出错误但也能正常工作?我已经阅读了这个问题的多个版本,但似乎找不到答案。提前感谢您的帮助。
switch (fork()){
case -1:
fprintf(stderr, "error forking");
case 0://CHILD
for(int j = 0; j < size; j++){
if(!strcmp(args[j], "<")){//looking for input character
++ext;
if((in = open(args[j+1], O_RDONLY)) < 0){//open file for reading
fprintf(stderr, "error opening file\n");
}
dup2(in, STDIN_FILENO);//duplicate stdin to input file
close(in);//close after use
//args[j] = NULL;
}//end input chech
if(!strcmp(args[j],">")){//looking for output character
++ext;
out = creat(args[j+1], 0644);//create new output file
dup2(out, STDOUT_FILENO);//redirect stdout to file
close(out);//close after usere
// args[j] = NULL;
}//end output check
if(!strcmp(args[j], ">>")){//looking for append
++ext;
int append = open(args[j+1],O_CREAT | O_RDWR | O_APPEND, 0644);
dup2(append, STDOUT_FILENO);
close(append);
// args[j] = NULL;
}
}//end loop
execvp(args[0],args);//execute in parent
fprintf(stderr, "error in child execi \n");//error
exit(0);
default://PARENT
wait(&status); //wait for child to finish
}//end switch
【问题讨论】:
-
您的意思是“shell 程序”(替代标准 shell,例如 Bash),还是“shell 脚本”(由特定 shell 运行的程序)?当心;程序不一定是脚本,如果你发布 C 源代码,你就不是在发布脚本——至少,使用传统的含义。另外,请注意,有一个特定的 C shell,它的语法与 Bash 和其他从 Bourne shell 派生的 shell 不同。因此,您可能是指“在用 C 编写的自定义 shell 程序中重定向 I/O”或类似的意思。
标签: c shell url-redirection