1

私は、perl スクリプトで次のデザインを持っています。

my $child_pid = fork;
if( ! $child_pid ){
    # do some stuff...
    exec( $user_specified_command );
else{
   # wait for child to exit
   waitpid( $child_pid, 0 );
}
# Continue with the script

子が実行されたときに親でアラートを受け取ることに興味があるので、詳細を取得できます$user_specified_command(具体的にはlsof、標準出力が通常のファイルにリダイレクトされているかどうかを確認するために使用します)。結果は次のようになります。

my $child_pid = fork;
if( ! $child_pid ){
    # do some stuff...
    exec( $user_specified_command );
else{
   # wait until the child exec's
   wait_child_exec();

   # do some stuff...

   # wait for child to exit
   waitpid( $child_pid, 0 );
}
# Continue with the script

名前が変わるまで出力をループしてgrepすることもできますpsが、 exec はより良い方法があるほど深刻なイベントのようです。

4

1 に答える 1

2

これに対する一般的なアプローチの 1 つは、子に継承される親にパイプを作成し、親にパイプの読み取り側をブロック (またはポーリング) させることです。

子が FD_CLOEXEC を持っていると仮定するか、適切な値の を持っていると仮定すると、$^F子の への呼び出しexec()はパイプの書き込み終了を閉じ、親の EOF を生成します。

# Run a command in a child process, returning to the parent only after
# the child process has called exec'd or, failing that, terminated.
#
# WARNING - this code not rigorously tested
#
sub spawn_patiently {
  my ($rd, $wr);

  return unless pipe($rd, $wr);
  # XXX This assumes $^F is less than fileno($wr)
  #     In practice, you'd want it to be less than fileno($rd), too

  my $pid = fork();
  return unless defined $pid;

  if (! $pid) {
    exec @_;
    die "exec: $!";
  }

  # parent - wait for child to exec
  close($wr);
  read($rd, my $dummy, 1);

  1;
}
于 2012-03-30T20:45:21.887 に答える