简体   繁体   English

如何在C中的Shell中执行带有多个参数的命令?

[英]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. 我不确定如何执行此操作,因为使用cat ,第二个参数始终是文本文件,但是使用ls等命令时,第二个参数却不是,因此我必须以不同的方式执行它。 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. 您的外壳程序应调用fork(),然后在子进程(其中fork()的返回值== 0)中,它将调用不同的exec命令之一来运行用户指定的程序。 Meanwhile, the original process is waiting on the fork'd child to complete with waitpid(). 同时,原始进程正在等待forkd的孩子完成waitpid()。

http://linux.die.net/man/3/exec 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). 将每个单词放在字符串数组上之后( "cat file.twt" => "cat", "file.txt" ),您可以调用exec *函数(例如:execve)。

For the execution, depending on what you need to do, you might need: 对于执行,根据您需要执行的操作,可能需要:

  • exec* functions (execve, execlp, etc.) exec *函数(execve,execlp等)
  • fork (since you're writing a shell, you need to keep your process alive) fork(由于您正在编写外壳程序,因此需要使进程保持活动状态)
  • wait/waitpid to avoid zombie processes 等待/等待,以避免僵尸进程
  • dup*/pipe if you need to play with file descriptiors. dup * / pipe(如果需要使用文件描述符)。

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) 最后,由于您正在编写外壳程序,因此您不必在乎每个二进制文件作为参数的期望,因为这不是外壳程序的工作(至少到此为止)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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