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

标签 c process fork execvp waitpid

我在尝试通过 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/

相关文章:

c - 为什么ESP指向[esp+0xc]?

c - 如何在 C 编程中泛化 SSCANF 和#DEFINE

.net - 如何控制.NET 2.0 中的进程关联?

perl - 从子堆栈中删除 Perl 模块

使用 os.pipe 和 os.fork() 问题的 Python 程序

c - fork() 期间重复的段?

c - 多线程程序C中的段错误

c - c中函数指针的用例

ruby - 讨论一个子进程,将 Ruby 与 IO 和线程一起使用

linux - 无法捕获命令进程 ID