In one of my courses we're writing our own shell (basically from scratch).
We've already handled writing a lexer and a parser to divide the input into nice "command" structures that are easier to deal with. Likewise, I have a function read_command()
that will read one command in at a time and figure out what type of command it is (pipe/and/or/simple/etc.).
I now am trying to write the execute_command(struct command cmd)
function that actually takes the command and runs it. I'm struggling on how to even start actually writing this function.
Let's say I just get a very simple cat foo.txt
as the command. My command structure will divide it up neatly so I have a word array with both words in it.
Now I want to run the cat
executable with the argument foo.txt
. I realize I should use the $PATH
variable to try to find the executable and then run it with this argument.
I'm struggling with a few major questions:
cat
? Keep in mind this program uses C. What functions can I use to search through directories? How do I use PATH to do this?cat
, how can I run it with foo.txt
as a parameter? How can this be done in C?getenv(3)
and its relatives. You probably don't actually need to directly do any operations on directories, but if you do, you can use opendir(3)
, readdir(3)
, closedir(3)
, etc.fork(2)
and execl(3)
or one of its relatives (execve(2)
is the base-level API).The man pages themselves or a simple google search for any of these functions will turn up plenty of examples to help you along.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With