2

我编写了一个使用 execl 函数的简单 C 程序。运行这个程序后我期望看到的是ps -U myusername.

ps -U myusername如果在终端中写入,我会得到想要的结果。

如果调用execl("/bin/ps", "/bin/ps", "-U myusername", NULL)我会收到以下错误消息error: improper list

但是,如果我从 中删除空格-U myusername,并按以下方式调用函数:execl("/bin/ps", "/bin/ps", "-Umyusername", NULL),我会得到正确的结果。

为什么会发生这种情况以及如何实现预期的行为(这只是一个简单的示例;我真正想要的是让用户输入命令并将其拆分为命令和参数,最后调用类似的东西execlp("command", "command", "arguments", NULL)。)?

4

1 回答 1

3

它是一个可变参数函数。就这样称呼它:

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 username。只需在控制台中输入它,它就会向您证明这一点;)

该行execlp("/bin/ps", "/bin/ps", "-U username", NULL);不起作用,因为它就像您ps '-U username'在 shell 中键入一样。'-U username'是单个参数,它不是有效参数ps

于 2016-04-20T10:07:49.850 回答