2017-03-13 1 views
0

終了し、親プロセスがwaitpid()を呼び出さないときにプロセスがゾンビにならないようにするLinuxまたはPOSIXメソッドがありますか?waitpidまで子プロセスをゾンビにしない

私は、親プロセスが、我々はSIGCHLDハンドラのSA_NOCLDSTOPを使用することができることを知っているが、親がビジー状態であるとSIGCHLDは、他のもののために使用されているので、それが私の場合はオプションではありません。

終了コードに興味がない場合は、特定の子プロセスを単独で静かに終了するようにマークする方法はありますか?

答えて

0

子プロセスを待つ必要がありますが、この手順に従うと、すぐに死ぬ子供を待つことができ、initに「本当の」プロセスを継承させることができます。 Initはあなたのために整理します。

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

void main(void) { 
    int ret; 
    pid_t child1; 
    pid_t child2; 
    int status; 

    child1 = fork(); 
    if (child1 == -1) { 
     /* error */ 
     exit(1); 
    } 

    if (child1 == 0) { 
     /* in the child... we create a new session, and then re-fork */ 
     setsid(); 

     child2 = fork(); 
     if (child2 == -1) { 
      exit(1); 
     } 

     if (child2 == 0) { 
      /* call execve() or a friend */ 
      ret = execlp("sleep", "sleep", "6", NULL); 

      /* we should _never_ get here - unless the execlp() fails */ 
      fprintf(stderr, "execlp() returned: %d\n", ret); 
      exit(1); 
      for(;;); 
     } 

     sleep(2); 

     /* success ... child1 dies here */ 
     exit(0); 
    } 

    sleep(4); 

    ret = waitpid(child1, &status, 0); 
    if (ret != 0) { 
     /* unfortunately we can only determine the state of our 'proxy' process... 
     * to get any further information/the child-child PID, then you'll need to use a pipe to share the information */ 
     fprintf(stderr, "waitpid() returned %d\n", ret); 
    } 

    sleep(4); 

    return; 
} 

様々な休止期間を使用すると、次のイベント(時計topか何かを)見ることができるはずです。 1

すべてのプロセスが起動

ステップ、シェル

  • 17336の子としてリンクされているすべての - 私のシェル
  • 21855 - アプリケーション
  • 21856 - CHILD1(プロキシプロセス)
  • 21857 - Child2(有用な子プロセス)

top出力:

attie 17336 17335 0 16:04 pts/36 00:00:00 -bash 
attie 21855 17336 0 16:34 pts/36 00:00:00 ./test 
attie 21856 21855 0 16:34 ?  00:00:00 ./test 
attie 21857 21856 0 16:34 ?  00:00:00 sleep 6 

ステップ2

CHILD1ダイ、及び/無効、CHILD2は(PID 1)initによって継承されますゾンビなる

attie 17336 17335 0 16:04 pts/36 00:00:00 -bash 
attie 21855 17336 0 16:34 pts/36 00:00:00 ./test 
attie 21856 21855 0 16:34 ?  00:00:00 [test] <defunct> 
attie 21857  1 0 16:34 ?  00:00:00 sleep 6 

ステップ3

子供1waidpid()

attie 17336 17335 0 16:04 pts/36 00:00:00 -bash 
attie 21855 17336 0 16:34 pts/36 00:00:00 ./test 
attie 21857  1 0 16:34 ?  00:00:00 sleep 6 

CHILD2が死んステップへの呼び出し中に親によってアップクリアされます、とinitによってアップクリアされます

attie 17336 17335 0 16:04 pts/36 00:00:00 -bash 
attie 21855 17336 0 16:34 pts/36 00:00:00 ./test 
関連する問題