I’m trying to implement a simple shell program that supports multiple piping. For now my shell can implement some simple builtin commands and also external commands. I did this by getting the user input from the command line which is separated by space " " and put each string in a char* argv[]. The problem now is executing pipes. I read a litle bit about it in this link http://www.cs.loyola.edu/~jglenn/702/S2005/Examples/dup2.html. And I understood how it works.
So I thought about strcmp each argv[i] with "|" and when I meet a pipe, I fork a new process. I then put the strings before the pipe in a char* argv[] and the one after the pipe in another char* argv[]. This might work for 1 pipe but if the user entered multiple have multiple pipes, things might get tedious with this method. My main problem is about separating the strings at both ends of the pipes. Any ideas on how I can implement it? Thanks.
Divide and conquer:
Step 3 is, due to C array semantics, pretty simple:
and then my_arguments is an array of length
pipe_positioncontaining the first arguments, andargumentsis an array of lengthargc - pipe_position - 1containing the rest. You can give these pointers to execvp without a problem. Yes, they point to the same block of memory, but that’s not execvp’s concern.