分叉过程的输出

时间:2011-10-13 07:23:07

标签: c linux fork

你好,我想问一个关于分叉的问题

这是代码

#include  <stdio.h>
#include  <string.h>
#include  <sys/types.h>

#define   MAX_COUNT  5
#define   BUF_SIZE   100

void  main(void)
{
     pid_t  pid;
     int    i;
     char   buf[BUF_SIZE];

     fork();
     pid = getpid();
     for (i = 1; i <= MAX_COUNT; i++) {
          sprintf(buf, "This line is from pid %d, value = %d\n", pid, i);
          write(1, buf, strlen(buf));
     } 
     printf("child id :%d\n" , pid);

     printf("parent id :%d\n" , getppid());
}

当我在这里运行它是输出

This line is from pid 31130, value = 1
This line is from pid 31130, value = 2
This line is from pid 31130, value = 3
This line is from pid 31130, value = 4
This line is from pid 31130, value = 5
child id :31130
This line is from pid 31131, value = 1
parent id :31052
This line is from pid 31131, value = 2
This line is from pid 31131, value = 3
This line is from pid 31131, value = 4
This line is from pid 31131, value = 5
child id :31131
parent id:31130

它真的让我困惑为什么

  1. 行父ID和子ID两次打印

  2. 为什么当我要求时,孩子的id值不同 只有一次

  3. 为什么第二次父ID值等于第一个子ID值

  4. 实际上是父母和智利的内容我非常感谢

3 个答案:

答案 0 :(得分:3)

函数fork调用一次,返回两次。因此,孩子和父母都要做printf s。

printf("child id :%d\n" , pid); /* Both child and parent print this. */
printf("parent id :%d\n" , getppid()); /* Both child and parent print this. */

你说“孩子”和“父母”的事实并没有真正改变任何事情,所以这就是你得到误导性结果的原因。

一种常见的模式是测试fork返回的值。它返回子节点中的0和父节点中子节点的PID。

pid_t pid = fork();
if (pid)
    printf("I am the parent, pid: %d. The child has pid: %d\n", getpid(), pid);
else
    printf("I am the child, pid: %d\n", getpid());

/* Common code. */
for...

答案 1 :(得分:2)

以下是您的问题的答案:

当您创建进程fork时,它实际上启动另一个进程 因此,在分叉后,所有内容都由主进程以及子进程执行,因此行父ID和子ID打印两次,并且它给出了不同的值,因为两者都由不同的进程执行,因此它们具有不同的id和不同的父id现在你的第三个问题的答案是在执行时第二个进程执行语句所以它的父进程是前一个进程所以第二次父id值等于第一个子id值。

我希望你能理解它。

答案 2 :(得分:0)

fork调用父和子执行相同的代码后

这是打印4个ID的原因

31131是您的子进程

31130其父母

31052是父母的父母

相关问题