簡體   English   中英

使用C中的switch語句進行分叉程序的程序

[英]Program Of forking processes using switch statement in C

我試圖按如下方式從父節點派生2個進程,但有時會出現錯誤(程序未完成),我也不知道為什么:

pid_t pidA, pidB;
pidA = fork();
switch (pidA) {
    case -1: 
        // error handling
        return -1;
    case 0:
        // first child code
        break;
    default: {
        // parent code 1
        pidB = fork();
        switch(pidB) {
            case -1:
                // error handling
                return -1;
            case 0:
                // second child code
                break;
            default:
                // parent code 2, I think it's the same like parent code 1. Am I right?
                waitpid(-1, NULL, 0);
                printf("parent\n");
                break;
         }
         // parent code 3, again same like parent code 1 and 2 ???
         // when I use printf("Parent\n"); here it prints Parent 2 times and I don't know why.
     }
 }

有人可以幫我這個忙,在這里找到問題所在。 一些解釋會很好。 謝謝

考慮流程樹:

    P
   / \
  P   C1
 / \
P  C2

第一叉 :分為P和C1

第二叉 :分為P和C2

C1返回並且不打印任何內容。

C2從開關中斷,打印Parent (注大寫p)並返回。

P打印parentParent

因此,這解釋了為什么它兩次打印Parent原因。


對於未完成的程序,請檢查waitpid()的返回值並嘗試相應地調試它。

您到底想在這里做什么? 當您第一次進行分叉時,您的第一個子進程實際上不會執行任何操作。 父級將恢復並再次派生返回pidB ,然后將繼續執行直到執行waitpid()函數。

我假設您正在嘗試等待新的子代代碼執行,然后在父代繼續打印“父代”之前終止。

您正在等待-1的PID,它可能應該是pidB

如果將printf()放在切換塊的外部,則子級將在輸出時打印“父級”,與生成它的父級相同。 如果您希望孩子立即終止,則可能需要return語句而不是break語句。

按原樣運行代碼,在第二個switch語句之外使用printf語句,這是我的輸出,使用pidB顯示正在打印的進程:

parent
Parent: pid=25046
Parent: pid=0

結果表明,孩子也是打印的孩子之一。

如果在內部開關案例0中添加收益而不是中斷,那么您將獲得:

parent
Parent: pid=25095

這是我的建議

// parent code 1
    pidB = fork();
    switch(pidB) {
        case -1:
            // error handling
            return -1;
        case 0:
             // second child code
             break;
        default:
            // parent code 2, I think it's the same like parent code 1. Am I right?
            waitpid(pidB, NULL, 0); // wait for the child process to finish by using the PID of the child as the argument to waitpid
            printf("parent\n");
            break;
     }
     // the child will execute anything here unless you return or otherwise prevent the child process from getting here.

暫無
暫無

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

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