IPC.pm 10 KB

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