簡體   English   中英

關於派生調用輸出的困惑

[英]Confusion about output of fork calls

考慮以下程序的輸出:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
void main()
{
    pid_t pid;
    int a = 5;
    pid = fork();
    if (pid == 0)
        printf("This is the son process, a = %d\n", --a);
    else
        printf("This is the dad process, a = %d\n", ++a);
}

我期望的輸出是:

This is the son process, a = 4;
This is the dad process, a = 6;

但是我得到的輸出為:

This is the son process, a = 4

那么,為什么父進程沒有執行printf呢? 如何獲得我想要的輸出?

更新:

剛才我再次嘗試,輸出如下:

$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
$ This is the son process, a = 4

現在仍然存在一個問題:為什么兩行輸出之間有一個$

我認為預期的輸出應該是這樣的:

$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
This is the son process, a = 4

我不知道為什么有$

更多細節:

gcc version: gcc 4.8.2  
OS: ubuntu 14.04

您需要檢查“分叉失敗”情況。 當fork()返回-1時,發生錯誤。 這是函數語義的一部分,因此,如果省略它,將會得到錯誤的結果。

請參閱此處的示例,其中考慮了fork失敗的可能性。

請參閱有關fork為何在此相關問題中失敗的討論。

$只是在過程輸出之間顯示的提示。 因為子級與父級“分離”運行,所以父級可能會在子級完成之前返回外殼。 因此,將打印提示,然后輸出孩子的輸出。 如果將所有輸出重定向到文件,則$不會在其中。

暫無
暫無

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

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