最詭異的Linux fork進程問題(我們平時都在寫)

來源:互聯網
上載者:User

標籤:io   sp   for   問題   代碼   bs   ef   linux   程式   

  從來沒有遇到過。。。

  運行環境:在Linux內建的文字編輯器中輸入C程式,在shell中編譯運行,下面直接看代碼和運行結果。

第一個代碼:#include<stdio.h>

      #include<stdlib.h>

      #include<unistd.h>

      #define N 2

      int main()

      {

        int i;

        pid_t pid;

        for(i = 0; i < N; i++)

        {

          pid = fork();

          if(pid == 0)

          {

            printf(" %d ",  0);

            exit(100+i);

          }

          else

flag:         printf(" %d ",  pid);

        }

        printf("over\n");

        exit(0);

      }

結果是:  0  2571  0  2571  2572  over

  第一段的結果在想了很久之後都沒能想通,為什麼第二個0後面會輸出兩個數呢?然後準備在flag標記的那個printf後加個"\n"讓其格式整齊一點發到部落格園上問大家呢,結果加了“\n”後輸出的結果卻是下面我寫的那樣,更迷糊了,希望哪位大俠知道幫忙解答一下。

第二段:把第一段的flag那行改為printf(" %d\n", getpid(), pid);

結果為:  0    2598

      0    2599

    over

 

最詭異的Linux fork進程問題(我們平時都在寫)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.