IPC.pm 8.2 KB

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