通过C中的fork()创建子进程

问题描述:

我完全不熟悉C并学习过程。我有点困惑,下面的代码实际上在做什么,它来自*,但我已经看到它在几本书中,我不确定为什么,例如,我们做pid_t pid;,然后pid = fork();。我的阅读似乎表明子进程返回pid0,但是,我认为在看到一棵树的根为pid 0后,非常原始的父进程将维持pid0通过C中的fork()创建子进程

什么,例如,pid = fork();对父母做什么?它不是对孩子做同样的事吗?并不pid = fork();把它放到一个循环,因为它会为每个孩子做到这一点?

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

#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; 
} 
+1

在POSIX系统上,_very first_处理它'init',它总是有进程ID 1.没有进程有进程ID为0. – 2013-04-05 13:23:14

+0

@JoachimPileborg如果是这种情况,那么为什么孩子的PID值过程,根据,我已经读了零?它不应该比父母更大吗? – mino 2013-04-05 13:44:53

+2

@mino:返回0的fork()的* point *是为了让它检测“aha,我在孩子身上”是微不足道的,因为你通常想在这种情况下做一些不同的事情(并且你自己的PID是很少有趣,并且可以使用'getpid()'快速找到)。 – unwind 2013-04-05 13:49:34

成功完成后,fork()source):

  • 应返回0给子进程
  • ,并应子进程的进程ID返回给父进程。

你给出的例子很好解释。但是,我想确切地说,两个过程(父母和孩子)都应该继续执行fork()函数。

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

+0

为什么你需要使用getpid f它会将子进程的pid返回给父进程? – mino 2013-04-05 14:08:21

+1

父进程将获得孩子的PID作为'fork()'函数的返回值。如果孩子想要获得自己的PID,则应使用'getpid()'调用。 – Bechir 2013-04-05 14:10:18

+0

我明白了,谢谢。 – mino 2013-04-05 14:11:52

fork是返回两次功能 - 一旦父,曾经为孩子。

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

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

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

如果您不测试fork()的返回值,那么这两个过程将完全相同。

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