创建多个子进程并运行execvp

标签 c linux fork execvp

我在 C 中有一个函数,它创建一个子进程并使其运行 execvp

int Execute(char **arg)
{
    pid_t pid;
    int status;

    if ((pid=fork()) == 0)
    {

        execvp(arg[0],arg);

        perror("Execvp error");
        exit(1);
    }

    else if (pid > 0)
    {
        waitpid(pid, &status, 0);
    }
    else
    {
        perror("Fork error");
        exit(2);
    }
}

现在我想更改该函数以实际运行 execvp 多次(例如 5),并让父进程等待所有子进程完成。尝试将其全部包装在 for 循环中,但 execvp 仅执行一次。我知道基本上 execvp 会“替换”当前的程序代码,但不知道迭代是否不会继续。

感谢您的帮助!

最佳答案

首先,循环创建进程并收集子 PID

pid_t pid[5];
int i;

for (i = 0; i < 5; i++) {
  if ((pid[i]=fork()) == 0) {
      execvp(arg[0],arg);

      perror("Execvp error");
      _exit(1);
  }
  if (pid[i] < 0) {
    perror("Fork error");
  }
}

其次,对每个有效的 PID 进行 waitpid 调用循环。

for (i = 0; i < 5; i++) { 
  if (pid[i] > 0) {
    int status;

    waitpid(pid[i], &status, 0);
    if (status > 0) {
      // handle a process sent exit status error
    }
  } else {
    // handle a proccess was not started
  }     
}

关于创建多个子进程并运行execvp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40551042/

相关文章:

android - 在linux shell脚本中执行程序

c - 使用函数将地址写入结构中的指针失败

c - 下面的链接列表代码给出了有趣的错误,你能检查一下吗?

android - 相同源代码的 .so 文件要小得多

检查子进程的状态

c - Unix 表示奇怪的行为。 ( child 多次退出)

python - 如何获取由双叉创建的守护进程的 pid?

C _ 求和函数没有给出期望的结果

c - 如何在不收到警告 `strtod` char "Assigning to ' const char *' from ' 的情况下复制 *' discards qualifier"等的功能?

c++ - linux中system()函数中waitpid()函数是如何实现的