IPC.pm 11 KB

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