IPC.pm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. # Copyright © 2008-2009 Raphaël Hertzog <hertzog@debian.org>
  2. # Copyright © 2008 Frank Lichtenheld <djpig@debian.org>
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. package Dpkg::IPC;
  17. use strict;
  18. use warnings;
  19. our $VERSION = "1.00";
  20. use Dpkg::ErrorHandling;
  21. use Dpkg::Gettext;
  22. use base qw(Exporter);
  23. our @EXPORT = qw(spawn wait_child);
  24. =head1 NAME
  25. Dpkg::IPC - helper functions for IPC
  26. =head1 DESCRIPTION
  27. Dpkg::IPC offers helper functions to allow you to execute
  28. other programs in an easy, yet flexible way, while hiding
  29. all the gory details of IPC (Inter-Process Communication)
  30. from you.
  31. =head1 METHODS
  32. =over 4
  33. =item spawn
  34. Creates a child process and executes another program in it.
  35. The arguments are interpreted as a hash of options, specifying
  36. how to handle the in and output of the program to execute.
  37. Returns the pid of the child process (unless the wait_child
  38. option was given).
  39. Any error will cause the function to exit with one of the
  40. Dpkg::ErrorHandling functions.
  41. Options:
  42. =over 4
  43. =item exec
  44. Can be either a scalar, i.e. the name of the program to be
  45. executed, or an array reference, i.e. the name of the program
  46. plus additional arguments. Note that the program will never be
  47. executed via the shell, so you can't specify additional arguments
  48. in the scalar string and you can't use any shell facilities like
  49. globbing.
  50. Mandatory Option.
  51. =item from_file, to_file, error_to_file
  52. Filename as scalar. Standard input/output/error of the
  53. child process will be redirected to the file specifed.
  54. =item from_handle, to_handle, error_to_handle
  55. Filehandle. Standard input/output/error of the child process will be
  56. dup'ed from the handle.
  57. =item from_pipe, to_pipe, error_to_pipe
  58. Scalar reference or object based on IO::Handle. A pipe will be opened for
  59. each of the two options and either the reading (C<to_pipe> and
  60. C<error_to_pipe>) or the writing end (C<from_pipe>) will be returned in
  61. the referenced scalar. Standard input/output/error of the child process
  62. will be dup'ed to the other ends of the pipes.
  63. =item from_string, to_string, error_to_string
  64. Scalar reference. Standard input/output/error of the child
  65. process will be redirected to the string given as reference. Note
  66. that it wouldn't be strictly necessary to use a scalar reference
  67. for C<from_string>, as the string is not modified in any way. This was
  68. chosen only for reasons of symmetry with C<to_string> and
  69. C<error_to_string>. C<to_string> and C<error_to_string> imply the
  70. C<wait_child> option.
  71. =item wait_child
  72. Scalar. If containing a true value, wait_child() will be called before
  73. returning. The return value will of spawn() will be a true value,
  74. but not the pid.
  75. =item nocheck
  76. Scalar. Option of the wait_child() call.
  77. =item timeout
  78. Scalar. Option of the wait_child() call.
  79. =item chdir
  80. Scalar. The child process will chdir in the indicated directory before
  81. calling exec.
  82. =item env
  83. Hash reference. The child process will populate %ENV with the items of the
  84. hash before calling exec. This allows exporting environment variables.
  85. =item delete_env
  86. Array reference. The child process will remove all environment variables
  87. listed in the array before calling exec.
  88. =back
  89. =cut
  90. sub _sanity_check_opts {
  91. my (%opts) = @_;
  92. internerr("exec parameter is mandatory in spawn()")
  93. unless $opts{"exec"};
  94. my $to = my $error_to = my $from = 0;
  95. foreach (qw(file handle string pipe)) {
  96. $to++ if $opts{"to_$_"};
  97. $error_to++ if $opts{"error_to_$_"};
  98. $from++ if $opts{"from_$_"};
  99. }
  100. internerr("not more than one of to_* parameters is allowed")
  101. if $to > 1;
  102. internerr("not more than one of error_to_* parameters is allowed")
  103. if $error_to > 1;
  104. internerr("not more than one of from_* parameters is allowed")
  105. if $from > 1;
  106. foreach (qw(to_string error_to_string from_string)) {
  107. if (exists $opts{$_} and
  108. (!ref($opts{$_}) or ref($opts{$_}) ne 'SCALAR')) {
  109. internerr("parameter $_ must be a scalar reference");
  110. }
  111. }
  112. foreach (qw(to_pipe error_to_pipe from_pipe)) {
  113. if (exists $opts{$_} and
  114. (!ref($opts{$_}) or (ref($opts{$_}) ne 'SCALAR' and
  115. not $opts{$_}->isa("IO::Handle")))) {
  116. internerr("parameter $_ must be a scalar reference or an IO::Handle object");
  117. }
  118. }
  119. if (exists $opts{"timeout"} and defined($opts{"timeout"}) and
  120. $opts{"timeout"} !~ /^\d+$/) {
  121. internerr("parameter timeout must be an integer");
  122. }
  123. if (exists $opts{"env"} and ref($opts{"env"}) ne 'HASH') {
  124. internerr("parameter env must be a hash reference");
  125. }
  126. if (exists $opts{"delete_env"} and ref($opts{"delete_env"}) ne 'ARRAY') {
  127. internerr("parameter delete_env must be an array reference");
  128. }
  129. return %opts;
  130. }
  131. sub spawn {
  132. my (%opts) = _sanity_check_opts(@_);
  133. $opts{"close_in_child"} ||= [];
  134. my @prog;
  135. if (ref($opts{"exec"}) =~ /ARRAY/) {
  136. push @prog, @{$opts{"exec"}};
  137. } elsif (not ref($opts{"exec"})) {
  138. push @prog, $opts{"exec"};
  139. } else {
  140. internerr("invalid exec parameter in spawn()");
  141. }
  142. my ($from_string_pipe, $to_string_pipe, $error_to_string_pipe);
  143. if ($opts{"to_string"}) {
  144. $opts{"to_pipe"} = \$to_string_pipe;
  145. $opts{"wait_child"} = 1;
  146. }
  147. if ($opts{"error_to_string"}) {
  148. $opts{"error_to_pipe"} = \$error_to_string_pipe;
  149. $opts{"wait_child"} = 1;
  150. }
  151. if ($opts{"from_string"}) {
  152. $opts{"from_pipe"} = \$from_string_pipe;
  153. }
  154. # Create pipes if needed
  155. my ($input_pipe, $output_pipe, $error_pipe);
  156. if ($opts{"from_pipe"}) {
  157. pipe($opts{"from_handle"}, $input_pipe) ||
  158. syserr(_g("pipe for %s"), "@prog");
  159. ${$opts{"from_pipe"}} = $input_pipe;
  160. push @{$opts{"close_in_child"}}, $input_pipe;
  161. }
  162. if ($opts{"to_pipe"}) {
  163. pipe($output_pipe, $opts{"to_handle"}) ||
  164. syserr(_g("pipe for %s"), "@prog");
  165. ${$opts{"to_pipe"}} = $output_pipe;
  166. push @{$opts{"close_in_child"}}, $output_pipe;
  167. }
  168. if ($opts{"error_to_pipe"}) {
  169. pipe($error_pipe, $opts{"error_to_handle"}) ||
  170. syserr(_g("pipe for %s"), "@prog");
  171. ${$opts{"error_to_pipe"}} = $error_pipe;
  172. push @{$opts{"close_in_child"}}, $error_pipe;
  173. }
  174. # Fork and exec
  175. my $pid = fork();
  176. syserr(_g("cannot fork for %s"), "@prog") unless defined $pid;
  177. if (not $pid) {
  178. # Define environment variables
  179. if ($opts{"env"}) {
  180. foreach (keys %{$opts{"env"}}) {
  181. $ENV{$_} = $opts{"env"}{$_};
  182. }
  183. }
  184. if ($opts{"delete_env"}) {
  185. delete $ENV{$_} foreach (@{$opts{"delete_env"}});
  186. }
  187. # Change the current directory
  188. if ($opts{"chdir"}) {
  189. chdir($opts{"chdir"}) || syserr(_g("chdir to %s"), $opts{"chdir"});
  190. }
  191. # Redirect STDIN if needed
  192. if ($opts{"from_file"}) {
  193. open(STDIN, "<", $opts{"from_file"}) ||
  194. syserr(_g("cannot open %s"), $opts{"from_file"});
  195. } elsif ($opts{"from_handle"}) {
  196. open(STDIN, "<&", $opts{"from_handle"}) || syserr(_g("reopen stdin"));
  197. close($opts{"from_handle"}); # has been duped, can be closed
  198. }
  199. # Redirect STDOUT if needed
  200. if ($opts{"to_file"}) {
  201. open(STDOUT, ">", $opts{"to_file"}) ||
  202. syserr(_g("cannot write %s"), $opts{"to_file"});
  203. } elsif ($opts{"to_handle"}) {
  204. open(STDOUT, ">&", $opts{"to_handle"}) || syserr(_g("reopen stdout"));
  205. close($opts{"to_handle"}); # has been duped, can be closed
  206. }
  207. # Redirect STDERR if needed
  208. if ($opts{"error_to_file"}) {
  209. open(STDERR, ">", $opts{"error_to_file"}) ||
  210. syserr(_g("cannot write %s"), $opts{"error_to_file"});
  211. } elsif ($opts{"error_to_handle"}) {
  212. open(STDERR, ">&", $opts{"error_to_handle"}) || syserr(_g("reopen stdout"));
  213. close($opts{"error_to_handle"}); # has been duped, can be closed
  214. }
  215. # Close some inherited filehandles
  216. close($_) foreach (@{$opts{"close_in_child"}});
  217. # Execute the program
  218. exec({ $prog[0] } @prog) or syserr(_g("exec %s"), "@prog");
  219. }
  220. # Close handle that we can't use any more
  221. close($opts{"from_handle"}) if exists $opts{"from_handle"};
  222. close($opts{"to_handle"}) if exists $opts{"to_handle"};
  223. close($opts{"error_to_handle"}) if exists $opts{"error_to_handle"};
  224. if ($opts{"from_string"}) {
  225. print $from_string_pipe ${$opts{"from_string"}};
  226. close($from_string_pipe);
  227. }
  228. if ($opts{"to_string"}) {
  229. local $/ = undef;
  230. ${$opts{"to_string"}} = readline($to_string_pipe);
  231. }
  232. if ($opts{"error_to_string"}) {
  233. local $/ = undef;
  234. ${$opts{"error_to_string"}} = readline($error_to_string_pipe);
  235. }
  236. if ($opts{"wait_child"}) {
  237. my $cmdline = "@prog";
  238. if ($opts{"env"}) {
  239. foreach (keys %{$opts{"env"}}) {
  240. $cmdline = "$_=\"" . $opts{"env"}{$_} . "\" $cmdline";
  241. }
  242. }
  243. wait_child($pid, nocheck => $opts{"nocheck"},
  244. timeout => $opts{"timeout"}, cmdline => $cmdline);
  245. return 1;
  246. }
  247. return $pid;
  248. }
  249. =item wait_child
  250. Takes as first argument the pid of the process to wait for.
  251. Remaining arguments are taken as a hash of options. Returns
  252. nothing. Fails if the child has been ended by a signal or
  253. if it exited non-zero.
  254. Options:
  255. =over 4
  256. =item cmdline
  257. String to identify the child process in error messages.
  258. Defaults to "child process".
  259. =item nocheck
  260. If true do not check the return status of the child (and thus
  261. do not fail it it has been killed or if it exited with a
  262. non-zero return code).
  263. =item timeout
  264. Set a maximum time to wait for the process, after that fail
  265. with an error message.
  266. =back
  267. =cut
  268. sub wait_child {
  269. my ($pid, %opts) = @_;
  270. $opts{"cmdline"} ||= _g("child process");
  271. internerr("no PID set, cannot wait end of process") unless $pid;
  272. eval {
  273. local $SIG{ALRM} = sub { die "alarm\n" };
  274. alarm($opts{"timeout"}) if defined($opts{"timeout"});
  275. $pid == waitpid($pid, 0) or syserr(_g("wait for %s"), $opts{"cmdline"});
  276. alarm(0) if defined($opts{"timeout"});
  277. };
  278. if ($@) {
  279. die $@ unless $@ eq "alarm\n";
  280. error(ngettext("%s didn't complete in %d second",
  281. "%s didn't complete in %d seconds",
  282. $opts{"timeout"}),
  283. $opts{"cmdline"}, $opts{"timeout"});
  284. }
  285. unless ($opts{"nocheck"}) {
  286. subprocerr($opts{"cmdline"}) if $?;
  287. }
  288. }
  289. 1;
  290. __END__
  291. =back
  292. =head1 AUTHORS
  293. Written by Raphaël Hertzog <hertzog@debian.org> and
  294. Frank Lichtenheld <djpig@debian.org>.
  295. =head1 SEE ALSO
  296. Dpkg, Dpkg::ErrorHandling