2016-05-14 5 views
0
//Why not execute all the conditions(parent and child)? 
#include<stdio.h> 
#include<unistd.h> 

int main(){ 
     pid_t pid; //process-id 
     printf("This is where we start...\n"); 
     pid = fork(); 
//For the child process 
     if(pid==0){ 
       printf("This is the child process!\n"); 
       return 1; 
     } 
//This should have been printed 
     if(pid>0){ 
       printf("This is the parent!\n"); 
     } 
//THis may/may not be printed - its ok 
     if(pid < 0){ 
       printf("Fork failed!"); 
     } 
     return 0; 
} 

子供から戻った後、親が実行されていたはずですが、これは私が取得したものです: $これは子プロセスです!「これは子プロセスです」という印刷後に実行が停止する理由は何ですか?

何が欠けていますか?どうして子ブロックだけでなく親ブロックも印刷されますか?

+3

私は子供を待たずに終了している参照のみの問題。どちらも印刷する必要があります。 – stark

+0

これはWindows版ですか? – stark

答えて

3

プログラムは完全に正常です。フォークが実行されると、新しい子プロセスが作成されます。作成された子プロセスは親から独立しており、子プロセスが完了するのを子プロセスが待つことはまったくない可能性があります。

子が完了した後に親の実行が再開されるようにするには、親が続行する前にforkされた子が実行されることを確認するwait()関数を使用する必要があります。次のようにコードを更新

試してみてください。

#include<stdio.h> 
#include<unistd.h> 
#include <sys/wait.h> //Add this header 

int main() 
{ 
     pid_t pid; //process-id 
     int status; //A variable to get the status of the child, i.e. if error or success 
     printf("This is where we start...\n"); 
     pid = fork(); 
     if(pid==0){ 
       printf("This is the child process!\n"); 
       return 1; 
     } 
     if(pid>0){ 
       wait(&status); //Function to wait for child 
       printf("This is the parent!\n"); 
     } 
     if(pid < 0){ 
       printf("Fork failed!"); 
     } 
     return 0; 
} 

詳細については、このリンクをチェックアウト:Forking a Process and Parent-Child execution - Linux : C Programming

+0

私はこの質問をあなたと今後のすべての読者にもお伝えしますが、 は 'return 1'と冗長ではありませんか? 実行は 'return 0'に到達します。 – hitter

+1

@wing:いいえ、冗長ではありません。なぜなら、 'return 0'に達すると' 1'を返すのではなく、 '0'を返すからです。 –

+0

親が子を待たない場合、子はゾンビのプロセスになります。 (ゾンビプロセスとしての非常に望ましくない状態は、再起動以外では除去できない)I.E.子供が出る前に親を殺すと、プロセスの既知のリストから子供が削除されるため、OSは子供を見つけることができません(I.E.ゾンビプロセス)。この回答の最初の段落は正しくありません。その詳細以外は、非常に良い答えです。 – user3629249

関連する問題