C语言 在 C 中通过 fork() 创建子进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15835045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:58:22  来源:igfitidea点击:

Child Process Creation through fork() in C

cprocessparent-childfork

提问by mino

I'm completely new to C and learning about processes. I'm a little confused as to what the code below is actually doing, it's taken from Wikipedia but I've seen it in several books and am unsure as to why, for example, we do pid_t pid;then pid = fork();. My reading seem to suggest the child process returns a pidof 0, however, I thought the very original parent process will maintain the pidof 0after seeing a tree with the root as pid 0.

我对 C 和学习过程完全陌生。我很困惑,什么下面的代码实际上是干什么的,它是从维基百科一点点,但我在几本书,看到它,我不确定为什么,例如,我们做pid_t pid;那么pid = fork();。我的阅读似乎表明子进程返回 a pidof 0,但是,我认为非常原始的父进程在看到根为 的树后会保持pidof 。0pid 0

What does, for example, pid = fork();do to the parent? As doesn't it do the same thing for the child? And doesn't pid = fork();put it into a loop as it will do this for each child?

例如,pid = fork();对父母做什么?因为它不为孩子做同样的事情吗?并且不会pid = fork();将其放入循环中,因为它会为每个孩子执行此操作?

Basically, could someone explain each step to me as if I were, say, five? Maybe younger? Thanks!

基本上,有人可以向我解释每一步,就好像我是五岁一样吗?也许更年轻?谢谢!

#include <stdio.h>   /* printf, stderr, fprintf */
#include <sys/types.h> /* pid_t */
#include <unistd.h>  /* _exit, fork */
#include <stdlib.h>  /* exit */
#include <errno.h>   /* errno */

int main(void)
{
   pid_t  pid;

   /* Output from both the child and the parent process
    * will be written to the standard output,
    * as they both run at the same time.
    */
   pid = fork();

   if (pid == -1)
   {
      /* Error:
       * When fork() returns -1, an error happened
       * (for example, number of processes reached the limit).
       */
      fprintf(stderr, "can't fork, error %d\n", errno);
      exit(EXIT_FAILURE);
   }
   else if (pid == 0)
   {
      /* Child process:
       * When fork() returns 0, we are in
       * the child process.
       */
      int  j;
      for (j = 0; j < 10; j++)
      {
         printf("child: %d\n", j);
         sleep(1);
      }
      _exit(0);  /* Note that we do not use exit() */
   }
   else
   {
      /* When fork() returns a positive number, we are in the parent process
       * (the fork return value is the PID of the newly created child process)
       * Again we count up to ten.
       */
      int  i;
      for (i = 0; i < 10; i++)
      {
         printf("parent: %d\n", i);
         sleep(1);
      }
      exit(0);
   }
   return 0;
}

采纳答案by Bechir

Upon successful completion, fork()(source):

成功完成后,fork()来源):

  • shall return 0 to the child process
  • and shall return the process ID of the child process to the parent process.
  • 应将 0 返回给子进程
  • 并将子进程的进程ID返回给父进程。

The example you gave is well explained. However, I would like to precise that Both processes (parent and child) shall continue to execute from the fork()function.

你举的例子很好解释。但是,我想明确指出,两个进程(父进程和子进程)都应继续从fork()函数中执行。

if you would like to know the PID of the child (from the code of the child), use getpidAPI.

如果您想知道孩子的 PID(从孩子的代码中),请使用getpidAPI

回答by user2194434

After executing the fork() function, you have two processes, which both continue executing after the fork call. The only difference between the two processes is the return value of fork(). In the original process, the "parent", the return value is the process id (pid) of the child. In the new cloned process, the "child", the return value is 0.

执行 fork() 函数后,您有两个进程,它们都在 fork 调用后继续执行。两个进程的唯一区别是 fork() 的返回值。在原始进程中,“父进程”,返回值是子进程的进程id(pid)。在新克隆的进程中,“子进程”,返回值为 0。

If you wouldn't test the return value of fork(), both processes would be doing exactly the same.

如果您不测试 fork() 的返回值,则两个进程将完全相同。

NB: to understand why the fork() function is useful, you need to read what the exec() function is doing. This function loads a new process from disk, and replaces the caller process with the new process. The combination of fork() and exec() is actually the way to start a different process.

注意:要了解 fork() 函数为何有用,您需要阅读 exec() 函数在做什么。该函数从磁盘加载一个新进程,并用新进程替换调用者进程。fork() 和 exec() 的组合实际上是启动不同进程的方式。

回答by Femaref

forkis a function that returns twice - once for the parent, once for the child.

fork是一个返回两次的函数 - 一次为父级,一次为子级。

For the child, it returns 0, for the parent the pid of the child, any positive number; for both processes, the execution continues after the fork.

对于孩子,它返回0,对于父母,孩子的pid,任何正数;对于这两个进程,在 fork 之后继续执行。

The child process will run through the else if (pid == 0)block, while the parent will run the elseblock.

子进程将运行该else if (pid == 0)块,而父进程将运行该else块。