IPC.pm 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 qw(error syserr subprocerr);
  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 chdir
  74. Scalar. The child process will chdir in the indicated directory before
  75. calling exec.
  76. =item env
  77. Hash reference. The child process will populate %ENV with the items of the
  78. hash before calling exec. This allows exporting environment variables.
  79. =item delete_env
  80. Array reference. The child process will remove all environment variables
  81. listed in the array before calling exec.
  82. =back
  83. =cut
  84. sub _sanity_check_opts {
  85. my (%opts) = @_;
  86. error("exec parameter is mandatory in fork_and_exec()")
  87. unless $opts{"exec"};
  88. my $to = my $error_to = my $from = 0;
  89. foreach (qw(file handle string pipe)) {
  90. $to++ if $opts{"to_$_"};
  91. $error_to++ if $opts{"error_to_$_"};
  92. $from++ if $opts{"from_$_"};
  93. }
  94. error("not more than one of to_* parameters is allowed")
  95. if $to > 1;
  96. error("not more than one of error_to_* parameters is allowed")
  97. if $error_to > 1;
  98. error("not more than one of from_* parameters is allowed")
  99. if $from > 1;
  100. foreach (qw(to_string error_to_string from_string
  101. to_pipe error_to_pipe from_pipe))
  102. {
  103. if (exists $opts{$_} and
  104. (!ref($opts{$_}) or ref($opts{$_}) ne 'SCALAR')) {
  105. error("parameter $_ must be a scalar reference");
  106. }
  107. }
  108. if (exists $opts{"env"} and ref($opts{"env"}) ne 'HASH') {
  109. error("parameter env must be a hash reference");
  110. }
  111. if (exists $opts{"delete_env"} and ref($opts{"delete_env"}) ne 'ARRAY') {
  112. error("parameter delete_env must be an array reference");
  113. }
  114. return %opts;
  115. }
  116. sub fork_and_exec {
  117. my (%opts) = _sanity_check_opts(@_);
  118. $opts{"close_in_child"} ||= [];
  119. my @prog;
  120. if (ref($opts{"exec"}) =~ /ARRAY/) {
  121. push @prog, @{$opts{"exec"}};
  122. } elsif (not ref($opts{"exec"})) {
  123. push @prog, $opts{"exec"};
  124. } else {
  125. error(_g("invalid exec parameter in fork_and_exec()"));
  126. }
  127. my ($from_string_pipe, $to_string_pipe, $error_to_string_pipe);
  128. if ($opts{"to_string"}) {
  129. $opts{"to_pipe"} = \$to_string_pipe;
  130. $opts{"wait_child"} = 1;
  131. }
  132. if ($opts{"error_to_string"}) {
  133. $opts{"error_to_pipe"} = \$error_to_string_pipe;
  134. $opts{"wait_child"} = 1;
  135. }
  136. if ($opts{"from_string"}) {
  137. $opts{"from_pipe"} = \$from_string_pipe;
  138. }
  139. # Create pipes if needed
  140. my ($input_pipe, $output_pipe, $error_pipe);
  141. if ($opts{"from_pipe"}) {
  142. pipe($opts{"from_handle"}, $input_pipe) ||
  143. syserr(_g("pipe for %s"), "@prog");
  144. ${$opts{"from_pipe"}} = $input_pipe;
  145. push @{$opts{"close_in_child"}}, $input_pipe;
  146. }
  147. if ($opts{"to_pipe"}) {
  148. pipe($output_pipe, $opts{"to_handle"}) ||
  149. syserr(_g("pipe for %s"), "@prog");
  150. ${$opts{"to_pipe"}} = $output_pipe;
  151. push @{$opts{"close_in_child"}}, $output_pipe;
  152. }
  153. if ($opts{"error_to_pipe"}) {
  154. pipe($error_pipe, $opts{"error_to_handle"}) ||
  155. syserr(_g("pipe for %s"), "@prog");
  156. ${$opts{"error_to_pipe"}} = $error_pipe;
  157. push @{$opts{"close_in_child"}}, $error_pipe;
  158. }
  159. # Fork and exec
  160. my $pid = fork();
  161. syserr(_g("fork for %s"), "@prog") unless defined $pid;
  162. if (not $pid) {
  163. # Define environment variables
  164. if ($opts{"env"}) {
  165. foreach (keys %{$opts{"env"}}) {
  166. $ENV{$_} = $opts{"env"}{$_};
  167. }
  168. }
  169. if ($opts{"delete_env"}) {
  170. delete $ENV{$_} foreach (@{$opts{"delete_env"}});
  171. }
  172. # Change the current directory
  173. if ($opts{"chdir"}) {
  174. chdir($opts{"chdir"}) || syserr(_g("chdir to %s"), $opts{"chdir"});
  175. }
  176. # Redirect STDIN if needed
  177. if ($opts{"from_file"}) {
  178. open(STDIN, "<", $opts{"from_file"}) ||
  179. syserr(_g("cannot open %s"), $opts{"from_file"});
  180. } elsif ($opts{"from_handle"}) {
  181. open(STDIN, "<&", $opts{"from_handle"}) || syserr(_g("reopen stdin"));
  182. close($opts{"from_handle"}); # has been duped, can be closed
  183. }
  184. # Redirect STDOUT if needed
  185. if ($opts{"to_file"}) {
  186. open(STDOUT, ">", $opts{"to_file"}) ||
  187. syserr(_g("cannot write %s"), $opts{"to_file"});
  188. } elsif ($opts{"to_handle"}) {
  189. open(STDOUT, ">&", $opts{"to_handle"}) || syserr(_g("reopen stdout"));
  190. close($opts{"to_handle"}); # has been duped, can be closed
  191. }
  192. # Redirect STDERR if needed
  193. if ($opts{"error_to_file"}) {
  194. open(STDERR, ">", $opts{"error_to_file"}) ||
  195. syserr(_g("cannot write %s"), $opts{"error_to_file"});
  196. } elsif ($opts{"error_to_handle"}) {
  197. open(STDERR, ">&", $opts{"error_to_handle"}) || syserr(_g("reopen stdout"));
  198. close($opts{"error_to_handle"}); # has been duped, can be closed
  199. }
  200. # Close some inherited filehandles
  201. close($_) foreach (@{$opts{"close_in_child"}});
  202. # Execute the program
  203. exec({ $prog[0] } @prog) or syserr(_g("exec %s"), "@prog");
  204. }
  205. # Close handle that we can't use any more
  206. close($opts{"from_handle"}) if exists $opts{"from_handle"};
  207. close($opts{"to_handle"}) if exists $opts{"to_handle"};
  208. close($opts{"error_to_handle"}) if exists $opts{"error_to_handle"};
  209. if ($opts{"from_string"}) {
  210. print $from_string_pipe ${$opts{"from_string"}};
  211. close($from_string_pipe);
  212. }
  213. if ($opts{"to_string"}) {
  214. local $/ = undef;
  215. ${$opts{"to_string"}} = readline($to_string_pipe);
  216. }
  217. if ($opts{"error_to_string"}) {
  218. local $/ = undef;
  219. ${$opts{"error_to_string"}} = readline($error_to_string_pipe);
  220. }
  221. if ($opts{"wait_child"}) {
  222. wait_child($pid, cmdline => "@prog");
  223. return 1;
  224. }
  225. return $pid;
  226. }
  227. =item wait_child
  228. Takes as first argument the pid of the process to wait for.
  229. Remaining arguments are taken as a hash of options. Returns
  230. nothing. Fails if the child has been ended by a signal or
  231. if it exited non-zero.
  232. Options:
  233. =over 4
  234. =item cmdline
  235. String to identify the child process in error messages.
  236. Defaults to "child process".
  237. =item nocheck
  238. If true do not check the return status of the child (and thus
  239. do not fail it it has been killed or if it exited with a
  240. non-zero return code).
  241. =back
  242. =cut
  243. sub wait_child {
  244. my ($pid, %opts) = @_;
  245. $opts{"cmdline"} ||= _g("child process");
  246. error(_g("no PID set, cannot wait end of process")) unless $pid;
  247. $pid == waitpid($pid, 0) or syserr(_g("wait for %s"), $opts{"cmdline"});
  248. unless ($opts{"nocheck"}) {
  249. subprocerr($opts{"cmdline"}) if $?;
  250. }
  251. }
  252. 1;
  253. __END__
  254. =back
  255. =head1 AUTHORS
  256. Written by Raphaël Hertzog <hertzog@debian.org> and
  257. Frank Lichtenheld <djpig@debian.org>.
  258. =head1 SEE ALSO
  259. Dpkg, Dpkg::ErrorHandling