簡體   English   中英

fork()子進程和父進程

[英]fork() child and parent processes

我正在嘗試創建一個使用fork()來創建新進程的程序。 示例輸出應如下所示:

這是子進程。 我的pid是733,我父母的id是772。
這是父進程。 我的pid是772,我孩子的id是773。

這是我編寫程序的方式:

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), fork());

    return 0;
}

這導致輸出:

這是子進程。 我的pid是22163,我父母的id是0。
這是子進程。 我的pid是22162,我父母的id是22163。

為什么它會兩次打印語句?如何在第一句中顯示子ID后如何正確顯示父語句?

編輯:

#include <stdio.h>
#include <stdlib.h>

int main() {
int pid = fork();

if (pid == 0) {
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid());
}
else {
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), pid);
}

return 0;
}

首先閱讀fork手冊頁以及getppid / getpid手冊頁。

從叉子

成功時,子進程的PID在父進程的執行中返回,並在子進程的執行中返回0。 失敗時,將在父上下文中返回-1,不會創建子進程,並且將正確設置errno。

所以這應該是一些事情

if ((pid=fork())==0){
    printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
    printf("Dont yada yada me, im your parent with pid %u ", getpid());
}

至於你的問題:

這是子進程。 我的pid是22163,我父母的id是0。

這是子進程。 我的pid是22162,我父母的id是22163。

fork()printf之前執行。 因此,當它完成時,您有兩個具有相同指令的進程。 因此,printf將執行兩次。 fork()的調用將返回0到子進程,子進程的pid返回到父進程。

您將獲得兩個正在運行的進程,每個進程都將執行此 指令 語句:

printf ("... My pid is %d and my parent's id is %d",getpid(),0); 

printf ("... My pid is %d and my parent's id is %d",getpid(),22163);  

要包裝它,上面的行是子,指定它的pid 第二行是父進程,指定其id(22162)及其子(22163)。

我們用if,else語句控制fork()進程調用。 請參閱下面的代碼:

int main()
{
   int forkresult, parent_ID;

   forkresult=fork();
   if(forkresult !=0 )
   {
        printf(" I am the parent my ID is = %d" , getpid());
        printf(" and my child ID is = %d\n" , forkresult);
   }
   parent_ID = getpid();

   if(forkresult ==0)
      printf(" I am the  child ID is = %d",getpid());
   else
      printf(" and my parent ID is = %d", parent_ID);
}

它正在打印語句兩次,因為它正在為父項和子項打印它。 父級的父ID為0

嘗試這樣的事情:

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid());
 else 
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid() );

這是獲取正確輸出的正確方法....但是,childs parent id有時可能打印為1,因為父進程終止,而pid = 1的根進程控制此孤立進程。

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id 
      is %d.\n", getpid(), getppid());
 else 
     printf("This is the parent process. My pid is %d and my parent's 
         id is %d.\n", getpid(), pid);

它打印兩次是因為你正在調用printf兩次,一次是在你的程序執行中,一次是在fork中。 嘗試從printf調用中取出fork()。

暫無
暫無

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

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