2

フォークを使用して子プロセスと親プロセスを作成し、パイプを使用してそれらの間でメッセージを送受信しています。いくつかの入力で親プロセスを実行しており、子プロセスを呼び出します。親プロセスが正常に実行されると、子プロセスは自動的に強制終了されますしかし、親プロセスの実行中にctrl + cを押すと、またはセグメンテーション違反がある場合、親プロセスは強制終了されますが、子プロセスは強制終了されません。

親プロセスが突然終了したときに子プロセスを強制終了するロジックを投稿できますか?

4

1 に答える 1

1

通信にはすでにパイプを使用しているため、これは簡単なはずです。

パイプは、読み取るデータが存在するまでブロックを読み取ります。親プロセスがライターであり、終了した場合は、EOFすぐに取得します。親プロセスが書き込み終了を閉じない場合は、死を検出する信頼できる方法があります。

リーダーが存在しないときにシグナルが無視された場合、パイプ書き込みはヒットし、呼び出しからSIGPIPE戻ります。EPIPE

子で、パイプの fd で (ブロックできる場合) を選択し、適切なタイミングでプロセスを強制終了します。SIGCHLD親の死に相当するものはありません。

man 7 pipeを参照してください。抜粋:

If  all file descriptors referring to the write end of a pipe have been closed, then an attempt to read(2) from
the pipe will see end-of-file (read(2) will return 0).  If all file descriptors referring to the read end of  a
pipe have been closed, then a write(2) will cause a SIGPIPE signal to be generated for the calling process.  If
the calling process is ignoring this signal, then write(2) fails with the error  EPIPE.   An  application  that
uses  pipe(2)  and  fork(2) should use suitable close(2) calls to close unnecessary duplicate file descriptors;
this ensures that end-of-file and SIGPIPE/EPIPE are delivered when appropriate.
于 2012-12-08T10:05:23.100 に答える