用C编写自己的shell,如何运行Unix可执行文件? [英] Writing my own shell in C, how do I run Unix executables?
问题描述
在我的一门课程中,我们正在编写自己的shell(基本上从头开始).
In one of my courses we're writing our own shell (basically from scratch).
我们已经处理过编写词法分析器和解析器,以将输入分为易于处理的漂亮命令"结构.同样,我有一个函数read_command()
,它可以一次读取一个命令,并弄清它是什么类型的命令(管道/和/或/简单/等).
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.).
我现在正在尝试编写execute_command(struct command cmd)
函数,该函数实际上接受命令并运行它.我正在为如何开始实际编写此功能而苦苦挣扎.
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.
比方说,我只是得到一个非常简单的cat foo.txt
作为命令.我的命令结构会将它整齐地分割,所以我有一个包含两个单词的单词数组.
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.
现在,我要使用参数foo.txt
运行cat
可执行文件.我意识到我应该使用$PATH
变量来尝试找到可执行文件,然后使用此参数运行它.
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
?请记住,该程序使用C.我可以使用哪些功能搜索目录?如何使用PATH来做到这一点? - 找到命令
cat
后,如何使用foo.txt
作为参数运行它?如何在C语言中完成此操作?
- 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? - When I do find the command
cat
, how can I run it withfoo.txt
as a parameter? How can this be done in C?
推荐答案
- 查看
getenv(3)
及其亲戚.您实际上可能实际上不需要直接对目录执行任何操作,但是如果这样做,则可以使用opendir(3)
,readdir(3)
,fork(2)
和execve(2)
是基本级别的API).
手册页本身或通过简单的google搜索这些功能中的任何一个,都会提供大量示例来帮助您.
The man pages themselves or a simple google search for any of these functions will turn up plenty of examples to help you along.
这篇关于用C编写自己的shell,如何运行Unix可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!