我在看教材时遇到一个问题——Unix系统编程
How big is the argument array passed as the second argument to
execvp
when you executeexeccmd
of Program 3.5 with the following command line?execcmd ls -l *.c
Answer: The answer depends on the number of
.c
files in the current directory because the shell expands*.c
before passing the command line toexeccmd
.
程序3.5:
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "restart.h"
int main(int argc, char *argv[]) {
pid_t childpid;
if (argc < 2){ /* check for valid number of command-line arguments */
fprintf (stderr, "Usage: %s command arg1 arg2 ...\n", argv[0]);
return 1;
}
childpid = fork();
if (childpid == -1) {
perror("Failed to fork");
return 1;
}
if (childpid == 0) {
execvp(argv[1], &argv[1]);
perror("Child failed to execvp the command");
return 1;
}
if (childpid != r_wait(NULL)) {
perror("Parent failed to wait");
return 1;
}
return 0;
}
为什么传递的参数数组的大小取决于当前目录中 .c 文件的数量?参数数组不就是这样的吗
argv[0] = "execcmd";
argv[1] = "ls";
argv[2] = "-l";
argv[3] = "*.c";
argv[4] = NULL;
更新:查找一个链接,很好地解释了 shell 扩展。可能对后来看到这篇文章但也不了解 shell 扩展的人有用。 Description about shell expansion
最佳答案
不,因为 shell 会进行通配符扩展。 它会在目录中查找与表达式匹配的文件,因此例如您可以使用“echo *.c”来发现 shell 将匹配的内容。然后它列出了 exec 调用中与 *.c 匹配的每个文件名,或者如果没有 *.c,则可能会导致有关找不到文件的错误消息。
shell 的扩展功能更加强大,相同的文件通配符立即可用于所有程序,如 cat、echo、ls、cc。
关于c - shell如何扩展*.c?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35191985/