IPC.pm 10 KB

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