我一直在编写一个自定义shell脚本,但在使用下面的代码重定向输出时出现了小错误。目前这段代码可以完美地工作,但是当传递给execvp args时,会抛出诸如(ls ">"没有此文件或目录)的错误。我知道这是因为它将整个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