13

fork()クライアント接続のハンドラーを生成するために使用するサーバーを作成しています。サーバーは、フォークされたプロセスに何が起こるかを知る必要はありません。プロセスは独自に動作し、完了すると、ゾンビになる代わりに死ぬだけです。これを達成する簡単な方法は何ですか?

4

3 に答える 3

14

いくつかの方法がありますが、親プロセスsigactionで withSA_NOCLDWAITを使用するのがおそらく最も簡単な方法です。

struct sigaction sigchld_action = {
  .sa_handler = SIG_DFL,
  .sa_flags = SA_NOCLDWAIT
};
sigaction(SIGCHLD, &sigchld_action, NULL);
于 2013-06-10T01:30:17.970 に答える
6

ダブルフォークを使用。子供たちにすぐに別のコピーをフォークさせ、元の子プロセスを終了させます。

http://thinkiii.blogspot.com/2009/12/double-fork-to-avoid-zombie-process.html

私の意見では、これはシグナルを使用するよりも簡単で、より理解しやすいものです。

void safe_fork()
{
  pid_t pid;
  if (!pid=fork()) {
    if (!fork()) {
      /* this is the child that keeps going */
      do_something(); /* or exec */
    } else {
      /* the first child process exits */
      exit(0);
    }
  } else {
    /* this is the original process */  
    /* wait for the first child to exit which it will immediately */
    waitpid(pid);
  }
}
于 2013-06-10T01:37:14.100 に答える