我在 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/