不能在C中使用execl

-4 c execl

我试图在C程序中执行此execl命令,它根本不起作用.

execl("~/Desktop/taskc/validating/analyzer/numbers_analyzer", "numbers_analyzer", (char*)NULL);

bash: syntax error near unexpected token `"~/Desktop/taskc/validating/analyzer/numbers_analyzer",
Run Code Online (Sandbox Code Playgroud)

我还尝试了一些我在互联网上找到的验证示例,但它们也不起作用.(我总是得到同样的错误)

execl( "/bin/ls", "/bin/ls", argv[1], NULL );
bash: syntax error near unexpected token `"/bin/ls",'

execl("/bin/date", "date", 0, 0);
bash: syntax error near unexpected token `"/bin/date",'
Run Code Online (Sandbox Code Playgroud)

感谢致敬.

dbu*_*ush 5

您获得的错误消息是,如果您尝试直接向shell输入C函数调用,会发生什么:

[dbush] execl("/bin/date", "date", 0, 0);
-bash: syntax error near unexpected token `"/bin/date",'
[dbush]
Run Code Online (Sandbox Code Playgroud)

您需要将代码放入实际的C程序,编译并运行它:

#include <stdio.h>
#include <unistd.h>

int main()
{
    // the last argument should be a NULL pointer to signal the end of the arg list
    execl("/bin/date", "date", NULL);
}
Run Code Online (Sandbox Code Playgroud)

输出:

[dbush] gcc  -g -o /tmp/x1 /tmp/x1.c
[dbush] /tmp/x1
Tue Nov 24 20:11:54 UTC 2015
Run Code Online (Sandbox Code Playgroud)

  • 并使用[wordexp()](http://man7.org/linux/man-pages/man3/wordexp.3.html)首先展开路径名称.它支持与POSIX shell相同的语法,因此`~`和`$ HOME`(和所有其他POSIX shell环境变量引用)都可以工作. (2认同)