IPC.pm 11 KB

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