I am working on a shell for a systems programming class. I have been having some trouble with the file redirection. I just got redirecting the output to work, e.x. "ls > a" however when I type a command like "cat < a" into my shell it deletes everything in the file. I feel like the problem stems from the second if statement- "fdin = open(_inputFile,777)"
If that is the case a link to a recommended tutorial / other examples would be much appreciated.
On a side note, I included the entire function, however at the point which it creates the pipe, I have not tested anything there yet. I don't believe it works properly either though, but that may be from a mistake in another file.
void Command:: execute(){
if(_numberOfSimpleCommands == 0){
prompt();
return;
}
//save input/output
int defaultin = dup(0);
int defaultout = dup(1);
//initial input
int fdin;
if(_inputFile){
fdin = open(_inputFile,0777);
}else{
//use default input
fdin = dup(defaultin);
}
//execution
int pid;
int fdout;
for(int i = 0; i < _numberOfSimpleCommands; i++){
dup2(fdin,0);
close(fdin);
//setoutput
if(i == _numberOfSimpleCommands -1){
if(_outFile){
fdout = creat(_outFile,0666);
}else{
fdout = dup(defaultout);
}
}else{
int fdpipe[2];
pipe(fdpipe);
fdout = fdpipe[0];
fdin = fdpipe[1];
}
dup2(fdout,1);
close(fdout);
开发者_StackOverflow社区 //create child
pid = fork();
if(pid == 0){
execvp(_simpleCommands[0]->_arguments[0],_simpleCommands[0]->_arguments);
perror("-myshell");
_exit(1);
}
}
//restore IO defaults
dup2(defaultin,0);
dup2(defaultout,1);
close(defaultin);
close(defaultout);
if(!_background){
waitpid(pid,0,0);
}
}
Your call open(_inputFile, 0777)
is incorrect. The second argument to open
is supposed to contain a bitwise or'd combination of values that specify access mode and file creation flags, among other things (O_RDONLY
, O_WRONLY
, etc). Since you're passing 0777
, that probably ends up containing both O_CREAT
and O_TRUNC
, which causes _inputFile
to be erased. You probably want open(_inputFile, O_RDONLY)
.
精彩评论