c - shell如何扩展*.c?

标签 c shell unix command-line

我在看教材时遇到一个问题——Unix系统编程

How big is the argument array passed as the second argument to execvp when you execute execcmd 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 to execcmd.

程序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/

相关文章:

python - 为什么某些 Unix 命令在从 Python 内部调用时不起作用? (找不到命令)

bash - 为什么 Bash 中的 [ -f ${x} ] 对于空 x 计算结果为 true?

linux - 意外的 Shell 脚本错误

linux - 在 linux 中两个文本文件之间做减法的方法

c++ - 将 vlfeat 库的 dsift 与 cv::Mat 结合使用

c - 如何运行子进程,并在 C 中与父进程一起操作?

c - 如何正确地将汇编程序转换为shellcode?

c - 如何在共享内存 fork 进程中使用互斥锁?

java - Java/JSch 中的 SSH 命令给出退出代码 -1

linux - 顶部 : counting the number of processes belonging to a user