IPC.pm 9.4 KB

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