程序:使用execlp()
系统调用列出当前文件夹中的所有C文件:
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Before Execl\n");
execlp("ls","ls","*.c",NULL); // this should print all c files in the current folder.
return 0;
}
节目输出:
Before Execl
ls: cannot access *.c: No such file or directory
每当我在搜索模式中使用“*
”时,我都会遇到类似的错误。请提出一些适当的解决方案。
答案 0 :(得分:2)
如果要扩展shell元字符,请调用shell以展开它们,因此:
execlp("sh", "sh", "-c", "ls *.c", (char *)0);
fprintf(stderr, "Failed to exec /bin/sh (%d %s)\n", errno, strerror(errno));
exit(EXIT_FAILURE);
请注意,如果execl()
或任何exec*
函数返回,则失败。你不需要测试它的状态;它失败了。您不应该exit(0);
(或return 0;
函数中的main()
),因为这表示成功。包含错误消息概述错误是有礼貌的,并且应将消息写入stderr
,而不是stdout
- 如图所示。
你可以自己做元字扩展; POSIX库中有一些函数可以帮助(例如glob()
)。但是让shell执行它会使整个堆更简单。
(我修改了上面的代码,使用execlp()
来符合问题的要求。如果我这样做不受约束,我可能会使用execl()
并指定{{1}而是作为第一个参数。)
答案 1 :(得分:1)
Exec不会处理“*
”运算符,因为shell会为您执行此操作。为此,请使用popen()
或glob_t
。您可以
获取有关2012-03-08我提出的类似question的详细信息。
答案 2 :(得分:-1)
应该是:
execlp("ls", "*.c", NULL);
答案 3 :(得分:-1)
execlp("ls", "*.c", NULL);
应该有效