c - C 中的 execvp 不通过 ar

标签 c exec

我正在尝试使用 exec 来执行作为参数给出的命令列表。

运行程序时的示例输入为 ./assn2 ls date。

当我这样做时,只执行第一个命令。

#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>


int main(int argc, char *argv[])
{
  int args = argc-1;

  pid_t childpid = fork();

  // error
  if (childpid < 0)
  {
    perror("fork() error");
    exit(-1);
  }

  // parent process
  if (childpid != 0)
  {
    printf("Parent Process started, now waiting for ID: %d\n", childpid);
    wait(NULL);
    printf("Parent Process resumeed. Child exit code 0. Now terminating\n");
    exit(0);
  }

  // child process
  if (args > 0)
  {
    printf("Child process has begun.  %d argument/s provided\n", args);

    int i;
    for (i = 1; i <= argc; i++)
    {
      execlp(argv[i], argv[i], NULL);
    }
    execvp(argv[1], argv);
  }
  else
  {
    printf("No arguments provided, terminating child\n");
  }

  return 0;
}

最佳答案

一旦第一个子进程执行(并成功),for 循环就不再继续,因为 execlp 只会用正在执行的命令替换当前进程镜像'ed.

你想要做的是遍历父进程中的命令行参数,并为每个命令执行一次。类似的东西可能就是您所追求的:

   for(int i = 1; i < argc; i++) {
       pid_t pid = fork();
       if (pid == 0) {
           execlp(argv[i] ,argv[i], (char*)0);
           perror("exec");
       } else if (pid > 0) {
           wait(NULL);
       } else {
           perror("fork");
           exit(1);
       }
  }

关于c - C 中的 execvp 不通过 ar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46370470/

相关文章:

c - 如何在C中打印数组中的数据?

c - IF 语句中的两个条件(C 语言)

c - C 编译器如何确定如何编译 f(enum)?

c++ - 一个 exec 函数中的多个终端命令

C - 如何将指针值返回给 main?

c - 正在重新分配的指针未分配

python - 重新定义在函数内不起作用的打印函数

php - exec 函数未按预期工作

android - 无法使用runtime.exec重新启动设备

c - 简单的 Linux Shell - execvp() 失败