Trying to write a shell that processes internal and external commands. I can get the internal commands and one external at a time.
My question is how to get a command like this to run: “ls -l | grep lib | wc -l”
I’m using a fork(), and passing external commands through execv() in a char*[].
Any thoughts on how to work this? I assume using pipe() or something, but I’m not sure.
Second part of the question: how about dealing with i/o redirection? Can anyone point me to somewhere helpful?
EDIT
So far, @Alex W is my hero. However, since I’m new to the pipe() and dup2() commands, I’m a little hesitant on what each call and variable are for.
Here’s the code I have that handles a single external command (Example = “ls -l -a”):
pid_t pid;
pid = fork();
if (pid < 0)
{
cout << "Fork failed." << endl;
}
else if (pid == 0)
{
execvp(exec_args[0], exec_args); //exec_args is a char*[] where
_exit (EXIT_FAILURE); //exec_args[0] contains "/bin/ls"
} //[1]="ls" and [2]="-l" [3]="-a"
else
{
int status;
waitpid(pid, &status, 0);
}
break;
You do use
pipeand in POSIX systems a pipe works in a similar manner to a file. You can write to a pipe and read from a pipe, but if there is nothing in the pipe it blocks. The best place to find information on Unix system calls is the man page for the system call. On a Unix system you would typeman pipeinto a terminal. If you don’t have access to a Unix terminal then just google “man pipe”. The nice thing about the man pages is they tell you what libraries to include for the given system call. Make sure you remember that when using anyexectype system call you are loading a completely new process into that memory and the process that you were executing will stop dead in its tracks.To use it do something like this: