IPC.pm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 or object based on IO::Handle. A pipe will be opened for
  58. each of the two options and either the reading (C<to_pipe> and
  59. C<error_to_pipe>) or the writing end (C<from_pipe>) will be returned in
  60. the referenced scalar. Standard input/output/error of the child process
  61. will be dup'ed to the other ends 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. if (exists $opts{$_} and
  107. (!ref($opts{$_}) or ref($opts{$_}) ne 'SCALAR')) {
  108. internerr("parameter $_ must be a scalar reference");
  109. }
  110. }
  111. foreach (qw(to_pipe error_to_pipe from_pipe)) {
  112. if (exists $opts{$_} and
  113. (!ref($opts{$_}) or (ref($opts{$_}) ne 'SCALAR' and
  114. not $opts{$_}->isa("IO::Handle")))) {
  115. internerr("parameter $_ must be a scalar reference or an IO::Handle object");
  116. }
  117. }
  118. if (exists $opts{"timeout"} and defined($opts{"timeout"}) and
  119. $opts{"timeout"} !~ /^\d+$/) {
  120. internerr("parameter timeout must be an integer");
  121. }
  122. if (exists $opts{"env"} and ref($opts{"env"}) ne 'HASH') {
  123. internerr("parameter env must be a hash reference");
  124. }
  125. if (exists $opts{"delete_env"} and ref($opts{"delete_env"}) ne 'ARRAY') {
  126. internerr("parameter delete_env must be an array reference");
  127. }
  128. return %opts;
  129. }
  130. sub fork_and_exec {
  131. my (%opts) = _sanity_check_opts(@_);
  132. $opts{"close_in_child"} ||= [];
  133. my @prog;
  134. if (ref($opts{"exec"}) =~ /ARRAY/) {
  135. push @prog, @{$opts{"exec"}};
  136. } elsif (not ref($opts{"exec"})) {
  137. push @prog, $opts{"exec"};
  138. } else {
  139. internerr("invalid exec parameter in fork_and_exec()");
  140. }
  141. my ($from_string_pipe, $to_string_pipe, $error_to_string_pipe);
  142. if ($opts{"to_string"}) {
  143. $opts{"to_pipe"} = \$to_string_pipe;
  144. $opts{"wait_child"} = 1;
  145. }
  146. if ($opts{"error_to_string"}) {
  147. $opts{"error_to_pipe"} = \$error_to_string_pipe;
  148. $opts{"wait_child"} = 1;
  149. }
  150. if ($opts{"from_string"}) {
  151. $opts{"from_pipe"} = \$from_string_pipe;
  152. }
  153. # Create pipes if needed
  154. my ($input_pipe, $output_pipe, $error_pipe);
  155. if ($opts{"from_pipe"}) {
  156. pipe($opts{"from_handle"}, $input_pipe) ||
  157. syserr(_g("pipe for %s"), "@prog");
  158. ${$opts{"from_pipe"}} = $input_pipe;
  159. push @{$opts{"close_in_child"}}, $input_pipe;
  160. }
  161. if ($opts{"to_pipe"}) {
  162. pipe($output_pipe, $opts{"to_handle"}) ||
  163. syserr(_g("pipe for %s"), "@prog");
  164. ${$opts{"to_pipe"}} = $output_pipe;
  165. push @{$opts{"close_in_child"}}, $output_pipe;
  166. }
  167. if ($opts{"error_to_pipe"}) {
  168. pipe($error_pipe, $opts{"error_to_handle"}) ||
  169. syserr(_g("pipe for %s"), "@prog");
  170. ${$opts{"error_to_pipe"}} = $error_pipe;
  171. push @{$opts{"close_in_child"}}, $error_pipe;
  172. }
  173. # Fork and exec
  174. my $pid = fork();
  175. syserr(_g("fork for %s"), "@prog") unless defined $pid;
  176. if (not $pid) {
  177. # Define environment variables
  178. if ($opts{"env"}) {
  179. foreach (keys %{$opts{"env"}}) {
  180. $ENV{$_} = $opts{"env"}{$_};
  181. }
  182. }
  183. if ($opts{"delete_env"}) {
  184. delete $ENV{$_} foreach (@{$opts{"delete_env"}});
  185. }
  186. # Change the current directory
  187. if ($opts{"chdir"}) {
  188. chdir($opts{"chdir"}) || syserr(_g("chdir to %s"), $opts{"chdir"});
  189. }
  190. # Redirect STDIN if needed
  191. if ($opts{"from_file"}) {
  192. open(STDIN, "<", $opts{"from_file"}) ||
  193. syserr(_g("cannot open %s"), $opts{"from_file"});
  194. } elsif ($opts{"from_handle"}) {
  195. open(STDIN, "<&", $opts{"from_handle"}) || syserr(_g("reopen stdin"));
  196. close($opts{"from_handle"}); # has been duped, can be closed
  197. }
  198. # Redirect STDOUT if needed
  199. if ($opts{"to_file"}) {
  200. open(STDOUT, ">", $opts{"to_file"}) ||
  201. syserr(_g("cannot write %s"), $opts{"to_file"});
  202. } elsif ($opts{"to_handle"}) {
  203. open(STDOUT, ">&", $opts{"to_handle"}) || syserr(_g("reopen stdout"));
  204. close($opts{"to_handle"}); # has been duped, can be closed
  205. }
  206. # Redirect STDERR if needed
  207. if ($opts{"error_to_file"}) {
  208. open(STDERR, ">", $opts{"error_to_file"}) ||
  209. syserr(_g("cannot write %s"), $opts{"error_to_file"});
  210. } elsif ($opts{"error_to_handle"}) {
  211. open(STDERR, ">&", $opts{"error_to_handle"}) || syserr(_g("reopen stdout"));
  212. close($opts{"error_to_handle"}); # has been duped, can be closed
  213. }
  214. # Close some inherited filehandles
  215. close($_) foreach (@{$opts{"close_in_child"}});
  216. # Execute the program
  217. exec({ $prog[0] } @prog) or syserr(_g("exec %s"), "@prog");
  218. }
  219. # Close handle that we can't use any more
  220. close($opts{"from_handle"}) if exists $opts{"from_handle"};
  221. close($opts{"to_handle"}) if exists $opts{"to_handle"};
  222. close($opts{"error_to_handle"}) if exists $opts{"error_to_handle"};
  223. if ($opts{"from_string"}) {
  224. print $from_string_pipe ${$opts{"from_string"}};
  225. close($from_string_pipe);
  226. }
  227. if ($opts{"to_string"}) {
  228. local $/ = undef;
  229. ${$opts{"to_string"}} = readline($to_string_pipe);
  230. }
  231. if ($opts{"error_to_string"}) {
  232. local $/ = undef;
  233. ${$opts{"error_to_string"}} = readline($error_to_string_pipe);
  234. }
  235. if ($opts{"wait_child"}) {
  236. my $cmdline = "@prog";
  237. if ($opts{"env"}) {
  238. foreach (keys %{$opts{"env"}}) {
  239. $cmdline = "$_=\"" . $opts{"env"}{$_} . "\" $cmdline";
  240. }
  241. }
  242. wait_child($pid, nocheck => $opts{"nocheck"},
  243. timeout => $opts{"timeout"}, cmdline => $cmdline);
  244. return 1;
  245. }
  246. return $pid;
  247. }
  248. =item wait_child
  249. Takes as first argument the pid of the process to wait for.
  250. Remaining arguments are taken as a hash of options. Returns
  251. nothing. Fails if the child has been ended by a signal or
  252. if it exited non-zero.
  253. Options:
  254. =over 4
  255. =item cmdline
  256. String to identify the child process in error messages.
  257. Defaults to "child process".
  258. =item nocheck
  259. If true do not check the return status of the child (and thus
  260. do not fail it it has been killed or if it exited with a
  261. non-zero return code).
  262. =item timeout
  263. Set a maximum time to wait for the process, after that fail
  264. with an error message.
  265. =back
  266. =cut
  267. sub wait_child {
  268. my ($pid, %opts) = @_;
  269. $opts{"cmdline"} ||= _g("child process");
  270. internerr("no PID set, cannot wait end of process") unless $pid;
  271. eval {
  272. local $SIG{ALRM} = sub { die "alarm\n" };
  273. alarm($opts{"timeout"}) if defined($opts{"timeout"});
  274. $pid == waitpid($pid, 0) or syserr(_g("wait for %s"), $opts{"cmdline"});
  275. alarm(0) if defined($opts{"timeout"});
  276. };
  277. if ($@) {
  278. die $@ unless $@ eq "alarm\n";
  279. error(ngettext("%s didn't complete in %d second",
  280. "%s didn't complete in %d seconds",
  281. $opts{"timeout"}),
  282. $opts{"cmdline"}, $opts{"timeout"});
  283. }
  284. unless ($opts{"nocheck"}) {
  285. subprocerr($opts{"cmdline"}) if $?;
  286. }
  287. }
  288. 1;
  289. __END__
  290. =back
  291. =head1 AUTHORS
  292. Written by Raphaël Hertzog <hertzog@debian.org> and
  293. Frank Lichtenheld <djpig@debian.org>.
  294. =head1 SEE ALSO
  295. Dpkg, Dpkg::ErrorHandling