gpt4 book ai didi

子进程在运行 fork() 时接管父进程

转载 作者:行者123 更新时间:2023-11-30 20:29:20 26 4
gpt4 key购买 nike

我在尝试通过 execvp() 运行多个命令时遇到问题。为此,我有一个 while 循环来执行每个命令,解析它,然后调用一个函数来使用 fork + exec。

问题是,我将运行 fork + exec,当我等待 exec 完成时,父级运行并继续第二个循环,即。第二个命令。但根据我的理解,发生的情况是上一个循环中的子进程接管,突然间,子进程就是当前进程。

如何在子进程中运行进程,同时在父进程中保持控制权?我在 SO 上看到的所有示例都是父进程等待子进程终止后再继续,但我在这个任务中没有选择 - 我应该保持子进程运行并稍后检查查看它们是否仍在运行。

这是我的思考过程的一些伪代码:

funct forkprocess() {
//call fork
//call execvp within child process, let process run and return control to parent
//if execvp failed, kill child process
//return child pid
}

int main() {
while(not end of file containing list of commands) :
//parse command for execvp call
//call forkprocess() to run process
//if childpid is returned, report it and store pid
//else, report failure
}
}

我的输出接近于以下内容:

\\parent PID is printed
\\any code outside the if-else ladder for fork is printed
\\it jumps back to main and prints any statements there

[jumps to next iteration in loop, ie. the next command]

\\child PID is printed
\\parent PID is printed
\\any code outside the if-else ladder for fork is printed
\\it jumps back to main and prints any statements there
\\child PID is printed

最佳答案

您需要确保仅在子级中调用 exec ,而不是在父级中调用。当 fork() 返回时,它会执行两次(一次在子级中,一次在父级中),并返回以下 values :

  • 如果我们在父级中,则非零(子级的 PID)。我们可以使用此 PID 来等待子进程终止,使用 waitpid .
  • 如果我们是 child ,则为零。
  • 如果 fork 失败则为负(在这种情况下,它只在父进程中返回一次,因为无法创建子进程)

您可能需要考虑使用以下结构:

int pid = fork();
if(pid < 0) {
perror("fork"); // remember to error check!
} else if (pid == 0) {
// We are in the child
// ...
if(execvp(...) < 0) {
perror("exec");
}
} else {
// We are in the parent; wait for the child to terminate using waitpid if desired.
waitpid(...);
}

为了简单起见,我在此处包含了 waitpid 调用;由于您的任务要求您保持子进程运行,因此您可以稍后使用该函数或通过处理 SIGCHLD 来检查它们的状态。

关于子进程在运行 fork() 时接管父进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58386362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com