使用 execl 调用带参数的 "ps" 命令有意外行为

Calling "ps" command with arguments with execl has unexpected behaviour

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

的输出

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

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

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

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

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

execlp("command", "command", "first arg", "second arg" /*, etc*/, NULL);

或者你的情况

execlp("/bin/ps", "/bin/ps", "-U", "username", NULL);

NULL 对函数说:"it is ok, there are no more arguments." 如果您忘记它,则存在未定义的行为。

更进一步:http://manpagesfr.free.fr/man/man3/stdarg.3.html

execlp("/bin/ps", "/bin/ps", "-Uusername", NULL); 有效,因为 ps -Uusernameps -U username 相同。只需在控制台中输入它,它就会证明这一点;)

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

的有效参数