… | |
… | |
482 | thing in an AnyEvent program, you I<have> to create at least one |
482 | thing in an AnyEvent program, you I<have> to create at least one |
483 | watcher before you C<fork> the child (alternatively, you can call |
483 | watcher before you C<fork> the child (alternatively, you can call |
484 | C<AnyEvent::detect>). |
484 | C<AnyEvent::detect>). |
485 | |
485 | |
486 | As most event loops do not support waiting for child events, they will be |
486 | As most event loops do not support waiting for child events, they will be |
487 | emulated by AnyEvent in most cases, in which the latency and race problems |
487 | emulated by AnyEvent in most cases, in which case the latency and race |
488 | mentioned in the description of signal watchers apply. |
488 | problems mentioned in the description of signal watchers apply. |
489 | |
489 | |
490 | Example: fork a process and wait for it |
490 | Example: fork a process and wait for it |
491 | |
491 | |
492 | my $done = AnyEvent->condvar; |
492 | my $done = AnyEvent->condvar; |
493 | |
493 | |
… | |
… | |
1640 | }; |
1640 | }; |
1641 | |
1641 | |
1642 | *child = sub { |
1642 | *child = sub { |
1643 | my (undef, %arg) = @_; |
1643 | my (undef, %arg) = @_; |
1644 | |
1644 | |
1645 | defined (my $pid = $arg{pid} + 0) |
1645 | my $pid = $arg{pid}; |
1646 | or Carp::croak "required option 'pid' is missing"; |
1646 | my $cb = $arg{cb}; |
1647 | |
1647 | |
1648 | $PID_CB{$pid}{$arg{cb}} = $arg{cb}; |
1648 | $PID_CB{$pid}{$cb+0} = $cb; |
1649 | |
1649 | |
1650 | unless ($CHLD_W) { |
1650 | unless ($CHLD_W) { |
1651 | $CHLD_W = AE::signal CHLD => \&_sigchld; |
1651 | $CHLD_W = AE::signal CHLD => \&_sigchld; |
1652 | # child could be a zombie already, so make at least one round |
1652 | # child could be a zombie already, so make at least one round |
1653 | &_sigchld; |
1653 | &_sigchld; |
1654 | } |
1654 | } |
1655 | |
1655 | |
1656 | bless [$pid, $arg{cb}], "AnyEvent::Base::child" |
1656 | bless [$pid, $cb+0], "AnyEvent::Base::child" |
1657 | }; |
1657 | }; |
1658 | |
1658 | |
1659 | *AnyEvent::Base::child::DESTROY = sub { |
1659 | *AnyEvent::Base::child::DESTROY = sub { |
1660 | my ($pid, $cb) = @{$_[0]}; |
1660 | my ($pid, $icb) = @{$_[0]}; |
1661 | |
1661 | |
1662 | delete $PID_CB{$pid}{$cb}; |
1662 | delete $PID_CB{$pid}{$icb}; |
1663 | delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} }; |
1663 | delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} }; |
1664 | |
1664 | |
1665 | undef $CHLD_W unless keys %PID_CB; |
1665 | undef $CHLD_W unless keys %PID_CB; |
1666 | }; |
1666 | }; |
1667 | }; |
1667 | }; |