PageRenderTime 67ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/System/Command/Reaper.pm

https://github.com/book/System-Command
Perl | 267 lines | 79 code | 31 blank | 157 comment | 18 complexity | 2835c085bd9acb8c2f1b3c84a1ea2816 MD5 | raw file
  1. package System::Command::Reaper;
  2. use strict;
  3. use warnings;
  4. use 5.006;
  5. use Carp;
  6. use Scalar::Util qw( weaken reftype );
  7. use POSIX ":sys_wait_h";
  8. use constant MSWin32 => $^O eq 'MSWin32';
  9. use constant HANDLES => qw( stdin stdout stderr );
  10. use constant STATUS => qw( exit signal core );
  11. for my $attr ( HANDLES ) {
  12. no strict 'refs';
  13. *$attr = sub { return $_[0]{$attr} };
  14. }
  15. for my $attr ( STATUS ) {
  16. no strict 'refs';
  17. *$attr = sub { $_[0]->is_terminated(); return $_[0]{$attr} };
  18. }
  19. sub new {
  20. my ($class, $command, $o) = @_;
  21. $o ||= {};
  22. my $self = bless { %$o, command => $command }, $class;
  23. # copy/weaken the important keys
  24. @{$self}{ pid => HANDLES } = @{$command}{ pid => HANDLES };
  25. weaken $self->{$_} for ( command => HANDLES );
  26. return $self;
  27. }
  28. # this is necessary, because kill(0,pid) is misimplemented in perl core
  29. my $_is_alive = MSWin32
  30. ? sub { return `tasklist /FO CSV /NH /fi "PID eq $_[0]"` =~ /^"/ }
  31. : sub { return kill 0, $_[0]; };
  32. sub is_terminated {
  33. my ($self) = @_;
  34. my $pid = $self->{pid};
  35. # Zed's dead, baby. Zed's dead.
  36. return $pid if !$_is_alive->($pid) and exists $self->{exit};
  37. # If that is a re-animated body, we're gonna have to kill it.
  38. return $self->_reap(WNOHANG);
  39. }
  40. sub _reap {
  41. my ( $self, $flags ) = @_;
  42. $flags = 0 if ! defined $flags;
  43. my $pid = $self->{pid};
  44. # REPENT/THE END IS/EXTREMELY/FUCKING/NIGH
  45. if ( !exists $self->{exit} and my $reaped = waitpid( $pid, $flags ) ) {
  46. # Well, it's a puzzle because, technically, you're not alive.
  47. my $zed = $reaped == $pid;
  48. carp "Child process already reaped, check for a SIGCHLD handler"
  49. if !$zed && !$System::Command::QUIET && !MSWin32;
  50. # What do you think? "Zombie Kill of the Week"?
  51. @{$self}{ STATUS() }
  52. = $zed
  53. ? ( $? >> 8, $? & 127, $? & 128 )
  54. : ( -1, -1, -1 );
  55. # Who died and made you fucking king of the zombies?
  56. if ( defined( my $cmd = $self->{command} ) ) {
  57. @{$cmd}{ STATUS() } = @{$self}{ STATUS() };
  58. # I know you're here, because I can smell your brains.
  59. my $o = $cmd->{options};
  60. defined reftype( $o->{$_} )
  61. and reftype( $o->{$_} ) eq 'SCALAR'
  62. and ${ $o->{$_} } = $self->{$_}
  63. for STATUS();
  64. }
  65. # I think it's safe to assume it isn't a zombie.
  66. print { $self->{th} } "System::Command xit[$pid]: ",
  67. join( ', ', map "$_: $self->{$_}", STATUS() ), "\n"
  68. if $self->{trace};
  69. return $reaped; # It's dead, Jim!
  70. }
  71. # Look! It's moving. It's alive. It's alive...
  72. return;
  73. }
  74. sub close {
  75. my ($self) = @_;
  76. # close all pipes
  77. my ( $in, $out, $err ) = @{$self}{qw( stdin stdout stderr )};
  78. $in and $in->opened and $in->close || carp "error closing stdin: $!";
  79. $out and $out->opened and $out->close || carp "error closing stdout: $!";
  80. $err and $err->opened and $err->close || carp "error closing stderr: $!";
  81. # and wait for the child (if any)
  82. $self->_reap();
  83. return $self;
  84. }
  85. sub DESTROY {
  86. my ($self) = @_;
  87. local $?;
  88. local $!;
  89. $self->close if !exists $self->{exit};
  90. }
  91. 1;
  92. __END__
  93. =pod
  94. =head1 NAME
  95. System::Command::Reaper - Reap processes started by System::Command
  96. =head1 SYNOPSIS
  97. This class is used for internal purposes.
  98. Move along, nothing to see here.
  99. =head1 DESCRIPTION
  100. The L<System::Command> objects delegate the reaping of child
  101. processes to System::Command::Reaper objects. This allows a user
  102. to create a L<System::Command> and discard it after having obtained
  103. one or more references to its handles connected to the child process.
  104. The typical use case looks like this:
  105. my $fh = System::Command->new( @cmd )->stdout();
  106. The child process is reaped either through a direct call to C<close()>
  107. or when the command object and all its handles have been destroyed,
  108. thus avoiding zombies (which would be reaped by the system at the end
  109. of the main program).
  110. This is possible thanks to the following reference graph:
  111. System::Command
  112. | | | ^|
  113. v v v !|
  114. in out err !|
  115. ^| ^| ^| !|
  116. !v !v !v !v
  117. System::Command::Reaper
  118. Legend:
  119. | normal ref
  120. ! weak ref
  121. The System::Command::Reaper object acts as a sentinel, that takes
  122. care of reaping the child process when the original L<System::Command>
  123. and its filehandles have been destroyed (or when L<System::Command>
  124. C<close()> method is being called).
  125. =head1 METHODS
  126. System::Command::Reaper supports the following methods:
  127. =head2 new
  128. my $reaper = System::Command::Reaper->new( $cmd, \%extra );
  129. Create a new System::Command::Reaper object attached to the
  130. L<System::Command> object passed as a parameter.
  131. An optional hash reference can be used to pass extra attributes to the object.
  132. =head2 close
  133. $reaper->close();
  134. Close all the opened filehandles of the main L<System::Command> object,
  135. reaps the child process, and updates the main object with the status
  136. information of the child process.
  137. C<DESTROY> calls C<close()> when the sentinel is being destroyed.
  138. =head2 is_terminated
  139. if ( $reaper->is_terminated ) {...}
  140. Returns a true value if the underlying process was terminated.
  141. If the process was indeed terminated, collects exit status, etc.
  142. =head2 Accessors
  143. The attributes of a System::Command::Reaper object are also accessible
  144. through a number of accessors.
  145. The object returned by C<new()> will have the following attributes defined
  146. (as copied from the L<System::Command> object that created the reaper):
  147. =over 4
  148. =item pid
  149. The PID of the underlying command.
  150. =item stdin
  151. A filehandle opened in write mode to the child process' standard input.
  152. =item stdout
  153. A filehandle opened in read mode to the child process' standard output.
  154. =item stderr
  155. A filehandle opened in read mode to the child process' standard error output.
  156. =back
  157. After the call to C<close()> or after C<is_terminated()> returns true,
  158. the following attributes will be defined:
  159. =over 4
  160. =item exit
  161. The exit status of the underlying command.
  162. =item core
  163. A boolean value indicating if the command dumped core.
  164. =item signal
  165. The signal, if any, that killed the command.
  166. =back
  167. =head1 AUTHOR
  168. Philippe Bruhat (BooK), C<< <book at cpan.org> >>
  169. =head1 ACKNOWLEDGEMENTS
  170. This scheme owes a lot to Vincent Pit who on #perlfr provided the
  171. general idea (use a proxy to delay object destruction and child process
  172. reaping) with code examples, which I then adapted to my needs.
  173. =head1 COPYRIGHT
  174. Copyright 2010-2016 Philippe Bruhat (BooK), all rights reserved.
  175. =head1 LICENSE
  176. This program is free software; you can redistribute it and/or modify it
  177. under the same terms as Perl itself.
  178. =cut