简体   繁体   中英

How can I execute a command with multiple arguments in my shell in C?

I want my shell to be able to run

cat file.txt 

as well as

ls -l

I'm not sure how to do this, because with cat the 2nd argument is always a text file, however, with commands such as ls the 2nd argument is not, so I have to execute it differently. I am not sure how to handle both cases properly.

Your shell should be looking for a matching binary for the first parameter and passing in all subsequent parameters as strings to that first program. Your shell isn't responsible for determining what the parameters mean, the program it runs is.

Your shell should call fork(), then in the child process (where the return value of fork() == 0), it will call one of the different exec commands to run the user-specified program. Meanwhile, the original process is waiting on the fork'd child to complete with waitpid().

http://linux.die.net/man/3/exec

You see that many of those take an array of character pointers as a parameter. You'll pass in the subsequent parameters to the exec'd binary for it to read in and parse itself.

One of the best ways to do so is to cut your string based on one or more separators (spaces, tabs, etc.) and fill an array with the resulting words. Once you have put each word on an array of strings ( "cat file.twt" => "cat", "file.txt" ), you can call exec* functions (ex: execve).

For the execution, depending on what you need to do, you might need:

  • exec* functions (execve, execlp, etc.)
  • fork (since you're writing a shell, you need to keep your process alive)
  • wait/waitpid to avoid zombie processes
  • dup*/pipe if you need to play with file descriptiors.

And lastly, since you're writing a shell, you shouldn't care about what each binary expects as arguments because it's not the job of a shell (well at least at this point)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM