IPC.pm 10 KB

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