簡體   English   中英

調用 fork() 時父進程未運行,函數不返回

[英]Parent process not running when calling fork(), function doesn't return

我正在使用fork()系統調用編寫最簡單的程序。 當我運行程序時,父進程似乎停止運行,並且函數永遠不會返回。

int main() {
    int x = 100;
    int fork_result = fork();
    if (fork_result < 0) {
        fprintf(stderr, "Fork failed.\n");
        exit(1);
    } else if (fork_result == 0) {
        printf("Child value before: %d\n", x);
        x = 200;
        printf("Child value after: %d\n", x);
    } else {
        printf("Parent value before: %d\n", x);
        x = 300;
        printf("Parent value after: %d\n", x);
    }
    return 0;
}

我在運行時得到的輸出是:

Child value before: 100
Child value after: 200

程序繼續無限期運行而不返回。 這里發生了什么?

謝謝。

當我編譯您的代碼時,由於缺少標頭和一些語法錯誤,編譯錯誤失敗。 修復那些它按我的預期運行的。 如果您將編譯器設置為忽略警告,或者當函數沒有正確原型化時可能會發生這種奇怪的事情。

出於教育目的,我在您的代碼中添加了一些額外的行。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <wait.h>

int main() {
    int x = 100;
    printf( "sizeof pid_t: %d\n", (int)sizeof(pid_t) );
    fflush( stdout );
    pid_t fork_result = fork();
    if (fork_result < 0) {
        fprintf(stderr, "Fork failed.\n");
        exit(1);
    } else if (fork_result == 0) {
        sleep(2);
        printf("Child value before: %d\n", x); 
        x = 200;
        printf("Child value after: %d\n", x); 
        printf("Child fork_result=%d\n", (int)fork_result);
        return(42);
    } else {
        printf("Parent value before: %d\n", x); 
        x = 300;
        printf("Parent value after: %d\n", x); 
        printf("Parent fork_result=%d\n", (int)fork_result);
        int   xit_stat;
        pid_t xit_wait = waitpid( fork_result, &xit_stat, 0 );
        printf("Parent sees exit=%d\n", xit_stat >> 8); 
    }   
    return 0;
}

在這里找到我同樣的問題:

https://unix.stackexchange.com/questions/23228/there-is-no-bash-indicator-prompt-after-a-forked-process-terminates

這給出了一個很好的答案,似乎正在發生什么。 感謝大家的回應。

暫無
暫無

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

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