//save in/out
int tmpin = dup(0);
int tmpout = dup(1);
//set initial input
int fdin;
if(_inputFile)
{
fdin = open(_inputFile, O_RDONLY | O_CREAT, S_IREAD | S_IWRITE);
}
else
{
//use default input
fdin = dup(tmpin);
}
int ret;
int fdout;
for(int i = 0; i < _numberOfSimpleCommands; i++)
{
//redirect input
dup2(fdin, 0);
close(fdin);
//setup output
if(i == _numberOfSimpleCommands-1)
{// last command must be set so output redirection is set
if(_outFile)
{
fdout = open(_outFile, O_WRONLY | O_CREAT, S_IREAD | S_IWRITE);
}
else
{
fdout = dup(tmpout);
}
}
else
{
//simple command
//create pipe
int fdpipe[2];
pipe(fdpipe);
fdout = fdpipe[0];
fdin = fdpipe[1];
}
//redirect output
dup2(fdout, 1);
close(fdout);
//create child process
ret = fork();
if(ret == 0)
{
execvp((*_simpleCommands)._arguments[0],(*_simpleCommands)._arguments);
perror("execvp");
exit(1);
}//if ret
}//for
//restore in/out defaults
dup2(tmpin, 0);
dup2(tmpout, 1);
close(tmpin);
close(tmpout);
if(!_background)
{
//wait for last command
waitpid(ret, 0, 0);
}
This is the code i have for the implementation of a shell that supports pipes and i/o redirection
So far this code has worked for one input and one outout redirection.
But will not work for pipeing, and i cannot for the life of me figure out why.
Ex. cat file1.cc | grep malloc
A simple command in my implementation is just a command with its arguments.
Any help would be great. Also please tell me if i need to clarify anything.