Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing my own shell in C, how do I run Unix executables?

Tags:

c

shell

path

unix

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:

  1. How do I actually search for the command 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?
  2. When I do find the command cat, how can I run it with foo.txt as a parameter? How can this be done in C?
like image 845
Casey Patton Avatar asked Jan 21 '12 03:01

Casey Patton


1 Answers

  1. Check out 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.
  2. Use 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.

like image 121
Carl Norum Avatar answered Oct 23 '22 06:10

Carl Norum