0


次のコードを使用してプロセスをフォークし、後で停止するように通知しています。

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

using namespace std;

sig_atomic_t stopFlag = 0;
void measurementSignalHandler(int sig) {
  stopFlag = 1;
}

int main(int argc, char **argv) {
  pid_t measurementPid = fork();

  switch(measurementPid) {
  case -1:
    // fork failed
    cerr << "Failed to create measurement process." << endl;
    exit(1);
  case 0:
    // child
    signal(SIGUSR1, measurementSignalHandler);
    while(stopFlag == 0) {
      sleep(1);
    }

    cout << "Done with measurements." << endl;
    return 42;
  default:
    // parent
    sleep(5);

    // I do not understand why this sleep is necessary.
    kill(measurementPid, SIGUSR1);
    cout << "Giving measurement process some time to clean up."
         << endl;
    sleep(3);

    int childExitStatus;
    waitpid(measurementPid, &childExitStatus, 1);
    if(WIFEXITED(childExitStatus)) {
      cout << "Measurement process returned "
           << WEXITSTATUS(childExitStatus)
           << "." << endl;
    }
    else if(WIFSIGNALED(childExitStatus)) {
      cout << "Measurement process was terminated by signal "
           << WTERMSIG(childExitStatus)
           << "." << endl;
    }
    else {
      cout << "Measurement process ended neither on its own "
           << "nor by signal." << endl;
    }

    return 0;
  }
}

このコードは (予想どおり) 次のように出力
します。
採寸して終了。
測定プロセスは 42 を返しました。

ただし、kill ステートメントの後に sleep ステートメントを省略すると、代わりに次のようになり
ます。
測定プロセスは信号 80 で終了しました
。測定は終了しました。

3 秒待つかどうかによって結果が異なるのはなぜですか? 子供が戻ってくるまで待つべきではありませんか? これは私のアプリケーションでは (現時点では) あまり重要ではありませんが、正しく行う方法を理解したいと思います。子プロセスに停止するように通知し、「適切に」終了するまで待ちたいと思います。

助けてくれてありがとう、
ルッツ

4

0 に答える 0