簡體   English   中英

cout << fork()是否准確地調用fork()?

[英]does cout << fork() acctully call fork()?

我對fork函數有問題。

cout << fork();

准確地調用fork()嗎? 我正在嘗試制作進程樹,但仍然不知道如何管理fork()函數。 我寫了簡單的代碼來說明它,但是它什么也沒解釋。

int mainPID = getpid();
cout << "Main process: " << mainPID << endl << endl;

cout << fork() << endl;
cout << getpid() << endl;
cout << getppid() << endl;

它返回:118、119、120程序結束,並在屏幕0、118、1上獲得另一個值。cout << fork()確實執行fork()嗎? 我以為我只得到與mainPID相關的值。

fork()返回兩次:一次在原始父進程中,一次也在子進程中。 在父進程中,它返回子進程的PID。 在子進程中,它返回0

在這兩個過程中,返回值都由cout <<打印。 這樣您將獲得多個輸出。

如果父進程快速完成,它將在子進程調用getppid()之前退出。 然后,子進程將由init進程(即PID 1繼承。 因此,當孩子進入cout << getppid() << endl;時,它打印1 cout << getppid() << endl;

0帶有cout << fork() << endl;子進程的返回值cout << fork() << endl;

118 from child pid cout << getpid() << endl;

父ID cout << getppid() << endl; 1 cout << getppid() << endl; 因為實際的父級已經退出,所以您的子進程已被放棄,所以它接受pid = 1的init作為新的父級。

我建議更改一些代碼以清楚地拆分子進程和父進程,例如:

if ((pid = fork()) == -1) return -1;

if (pid == 0) 
    {
    //source for child process
    }else{
    //source for parent process
    }

暫無
暫無

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

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