我编写了一个使用 execl 函数的简单 C 程序。运行该程序后我期望看到的是 ps -U myusername
的输出。
如果在终端中写入 ps -U myusername
,我会得到所需的结果。
如果调用execl("/bin/ps", "/bin/ps", "-U myusername", NULL)
,我收到以下错误消息错误:不正确的列表
.
但是,如果我删除 -U myusername
中的空格,并按以下方式调用该函数: execl("/bin/ps", "/bin/ps", "-Umyusername", NULL)
,我得到了正确的结果。
为什么会发生这种情况以及如何实现预期的行为(这只是一个简单的示例;我真正想要的是让用户输入命令并将其拆分为命令和参数,最后调用类似 execlp("命令", "命令", "参数", NULL)
.)?
最佳答案
这是一个可变参数函数。就像这样调用它:
execlp("command", "command", "first arg", "second arg" /*, etc*/, NULL);
或者根据你的情况
execlp("/bin/ps", "/bin/ps", "-U", "username", NULL);
NULL
对函数说:“没关系,没有更多的参数了。”如果您忘记了它,则会出现未定义的行为。
进一步:http://manpagesfr.free.fr/man/man3/stdarg.3.html
行 execlp("/bin/ps", "/bin/ps", "-Uusername", NULL);
行有效,因为 ps -Uusername
是与ps -U 用户名
相同。只需在控制台中输入它,它就会向您证明这一事实;)
行 execlp("/bin/ps", "/bin/ps", "-U username", NULL);
不起作用,因为就好像您键入 在 shell 中 ps '-U username'
。 '-U username'
是单个参数,不是 ps
关于使用 execl 调用带有参数的 "ps"命令会出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36740348/