IPC.pm 10 KB

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