簡體   English   中英

分叉過程的輸出

[英]output of forking process

你好,我想問一個關於分叉的問題

這是代碼

#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值

父母和智利ID到底多謝了

函數fork被調用一次,並返回兩次 因此,孩子和父母都執行printf

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...

以下是您的問題的答案:

當您創建一個流程分支時,它實際上會啟動另一個流程,因此在分叉之后,主流程以及子流程都將執行所有操作,因此,行父ID和子ID分別打印了兩次,並且每次都給出了不同的值,因為兩者都被執行通過不同的進程,因此它們具有不同的ID和不同的父ID,現在您的第三個問題的答案是在執行該語句時,第二個進程正在執行該語句,因此其父級是上一個進程,因此第二次父ID值等於第一個子ID值。

希望您能理解。

在fork調用后,父母和孩子執行相同的代碼

這就是打印4個ID的原因

31131是您的子進程

31130其父

31052是父母的父母

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM