web-dev-qa-db-ja.com

子プロセスの死を追跡する

子プロセスが強制終了されるまで親プロセスを待機させずに、子プロセスの停止を追跡するにはどうすればよいですか?

サーバーがクライアントからの接続を受け入れ、受け入れるすべての接続に対して新しいプロセスをフォークするクライアントサーバーシナリオを試しています。

ゾンビの作成を防ぐためにSIGCHLDシグナルを無視しています。

_signal(SIGCHLD, SIG_IGN);
while(1)
{
  accept();
  clients++;
  if(fork() ==0)
  {
     childfunction();
     clients--;
  }
  else
  {
  }
}
_

上記のシナリオの問題は、子プロセスがchildfunction()関数で強制終了された場合、グローバル変数clientsがデクリメントされないことです。

注: SIGCHLDシグナルを使用せずに解決策を探しています...可能であれば

21
codingfreak

通常、pid _-1_でwaitpid()を呼び出すSIGCHLDのハンドラーを記述します。そこからの戻り値を使用して、どのpidが停止したかを判別できます。例えば:

_void my_sigchld_handler(int sig)
{
    pid_t p;
    int status;

    while ((p=waitpid(-1, &status, WNOHANG)) != -1)
    {
       /* Handle the death of pid p */
    }
}

/* It's better to use sigaction() over signal().  You won't run into the
 * issue where BSD signal() acts one way and Linux or SysV acts another. */

struct sigaction sa;

memset(&sa, 0, sizeof(sa));
sa.sa_handler = my_sigchld_handler;

sigaction(SIGCHLD, &sa, NULL);
_

または、子のプロセスIDを指定してwaitpid(pid, &status, 0)を呼び出し、同期的に子のプロセスIDが終了するのを待つこともできます。または、WNOHANGを使用して、ブロックせずにステータスを確認します。

26
asveikau

これまでのところ、質問の要求としてSIGCHLDを使用しないアプローチを提供するソリューションはありません。 この回答 で概説されている poll を使用した代替アプローチの実装を次に示します(これは、このような状況でSIGCHLDの使用を避ける必要がある理由も説明しています):

作成する各子プロセスとの間のパイプがあることを確認してください。 stdin/stdout/stderrまたは単なる追加のダミーfdのいずれかです。子プロセスが終了すると、パイプの終わりが閉じられ、メインイベントループがそのファイル記述子のアクティビティを検出します。閉じたという事実から、子プロセスが終了したことを認識し、waitpidを呼び出してゾンビを刈り取ります。

(注:簡潔にするために、エラーチェックやファイル記述子のクリーンアップなどのいくつかのベストプラクティスを省略しました)

/**
 * Specifies the maximum number of clients to keep track of.
 */
#define MAX_CLIENT_COUNT 1000

/**
 * Tracks clients by storing their process IDs and pipe file descriptors.
 */
struct process_table {
    pid_t clientpids[MAX_CLIENT_COUNT];
    struct pollfd clientfds[MAX_CLIENT_COUNT];
} PT;

/**
 * Initializes the process table. -1 means the entry in the table is available.
 */
void initialize_table() {
    for (int i = 0; i < MAX_CLIENT_COUNT; i++) {
        PT.clientfds[i].fd = -1;
    }
}

/**
 * Returns the index of the next available entry in the process table.
 */
int get_next_available_entry() {
    for (int i = 0; i < MAX_CLIENT_COUNT; i++) {
        if (PT.clientfds[i].fd == -1) {
            return i;
        }
    }
    return -1;
}

/**
 * Adds information about a new client to the process table.
 */
void add_process_to_table(int i, pid_t pid, int fd) {
    PT.clientpids[i] = pid;
    PT.clientfds[i].fd = fd;
}

/**
 * Removes information about a client from the process table.
 */
void remove_process_from_table(int i) {
    PT.clientfds[i].fd = -1;
}

/**
 * Cleans up any dead child processes from the process table.
 */
void reap_zombie_processes() {
    int p = poll(PT.clientfds, MAX_CLIENT_COUNT, 0);

    if (p > 0) {
        for (int i = 0; i < MAX_CLIENT_COUNT; i++) {
            /* Has the pipe closed? */
            if ((PT.clientfds[i].revents & POLLHUP) != 0) {
                // printf("[%d] done\n", PT.clientpids[i]);
                waitpid(PT.clientpids[i], NULL, 0);
                remove_process_from_table(i);
            }
        }
    }
}

/**
 * Simulates waiting for a new client to connect.
 */
void accept() {
    sleep((Rand() % 4) + 1);
}

/**
 * Simulates useful work being done by the child process, then exiting.
 */
void childfunction() {
    sleep((Rand() % 10) + 1);
    exit(0);
}

/**
 * Main program
 */
int main() {
    /* Initialize the process table */
    initialize_table();

    while (1) {
        accept();

        /* Create the pipe */
        int p[2];
        pipe(p);

        /* Fork off a child process. */
        pid_t cpid = fork();

        if (cpid == 0) {
            /* Child process */
            close(p[0]);
            childfunction();
        }
        else {
            /* Parent process */
            close(p[1]);
            int i = get_next_available_entry();
            add_process_to_table(i, cpid, p[0]);
            // printf("[%d] started\n", cpid);
            reap_zombie_processes();
        }
    }

    return 0;
}

そして、これがprintfステートメントをコメントなしで実行したときのサンプル出力です。

[31066] started
[31067] started
[31068] started
[31069] started
[31066] done
[31070] started
[31067] done
[31068] done
[31071] started
[31069] done
[31072] started
[31070] done
[31073] started
[31074] started
[31072] done
[31075] started
[31071] done
[31074] done
[31081] started
[31075] done
7
Michael Harvey

あなたはゾンビを望んでいません。子プロセスが停止し、親がまだ実行中であるが、ステータスを収集するためにwait()/waitpid()呼び出しを発行しない場合、システムは子とゾンビに関連付けられたリソースを解放しません。/defunctプロセスはprocテーブルに残されます。

SIGCHLDハンドラーを次のようなものに変更してみてください。

_
void chld_handler(int sig) {
    pid_t p;
    int status;

    /* loop as long as there are children to process */
    while (1) {

       /* retrieve child process ID (if any) */
       p = waitpid(-1, &status, WNOHANG);

       /* check for conditions causing the loop to terminate */
       if (p == -1) {
           /* continue on interruption (EINTR) */
           if (errno == EINTR) {
               continue;
           }
           /* break on anything else (EINVAL or ECHILD according to manpage) */
           break;
       }
       else if (p == 0) {
           /* no more children to process, so break */
           break;
       }

       /* valid child process ID retrieved, process accordingly */
       ...
    }   
}
_

オプションで、sigprocmask()を使用して、シグナルハンドラーの実行中に追加のSIGCHLDシグナルをマスク/ブロックすることができます。信号処理ルーチンが終了したら、ブロックされたマスクを元の値に戻す必要があります。

本当にSIGCHLDハンドラーを使用したくない場合は、定期的に呼び出される場所に子処理ループを追加して、終了した子をポーリングしてみてください。

2
jschmier

変数「clients」はfork()の後の異なるプロセスアドレス空間にあり、子の変数をデクリメントしても、これは親の値には影響しません。カウントを正しく処理するには、SIGCHLDを処理する必要があると思います。

1
trojanfoe