簡體   English   中英

C中的並行編程不執行指令

[英]Parallel programming in C not executing instructions

我需要 C 並行編程方面的幫助,來自這張圖: graph image

我寫了這段代碼:

#include <stdio.h>
#include <stdlib.h>
int main ()
{
    int r2;
    printf("---------   Program start   ---------");
    printf("\nBlock A instructions"); //block A
    printf("\nBlock B instructions"); //block B
    r2= fork();
    if (r2==0){ //child
        printf("\nBlock E instructions"); //block E
        printf("\nBlock F instructions"); //block F
        exit(0);
    }
    else{
        if (r2>0){ //father
            printf("\nBlock C instructions"); //block C
            printf("\nBlock D instructions"); //block D
            exit(0);
        }
        else printf("\nError");
    }
    printf("\nBlock G instructions"); //block G
    printf("\nBlock H instructions"); //block H
    printf("\n---------   Program finish   ---------");
}

輸出是:

---------   Program start   ---------
Block A instructions
Block B instructions
Block E instructions
Block F instructionsBlock B instructions
Block C instructions
Block D instructions

為什么程序不寫其他指令,為什么它寫了兩次“塊B指令”?

- - - - - - - - - - - 編輯: - - - - - - - - - - -

新代碼是:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main ()
{
    printf("---------   Program start   ---------\n");
    printf("Block A instructions\n"); //block A
    printf("Block B instructions\n"); //block B
    fflush(stdout);
    pid_t r2= fork();
    if (r2==0){ //child
        printf("Block E instructions\n"); //block E
        printf("Block F instructions\n"); //block F
        fflush(stdout);
        exit(1);
    }
    else{
        if (r2>0){ //father
            printf("Block C instructions\n"); //block C
            printf("Block D instructions\n"); //block D
            fflush(stdout);
            wait(NULL); //wait for child process to join with this parent, returns no value
        }
        else printf("Error");
    }
    printf("Block G instructions\n"); //block G
    printf("Block H instructions\n"); //block H
    printf("---------   Program finish   ---------");
    return 0;
}

現在的輸出是:

---------   Program start   ---------
Block A instructions
Block B instructions
Block E instructions
Block F instructions
Block C instructions
Block D instructions
Block G instructions
Block H instructions
---------   Program finish   ---------

有時C和D指令寫在E和F指令之前,這是正常的還是應該總是EF --> CD? 順便說一句,代碼是好的還是有一些錯誤? 我用 -Wall 編譯它,但沒有收到任何錯誤消息

<stdio.h>緩沖,請參閱stdio(3)setvbuf(3) 您應該在適當的地方調用fflush(3) ,特別是在fork(2)之前。

順便說一句,您的標准 libc 的代碼是自由軟件,可能是GNU glibc 當然它使用syscalls(2) 所以你應該研究它的源代碼。

另請閱讀如何調試小程序

printf("\\nBlock C instructions");

容易出錯。 \\n可以刷新緩沖區,實際上應該用作printf(3)控制格式字符串的最后一個字符。

由於exit(0) ,它不會打印其他指令,因此它永遠不會到達 G 和 H 塊。 對於 B 被打印兩次,請參閱 Basile Starynkevitch 的回答。

暫無
暫無

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

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