PageRenderTime 25ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Proc/Fork.pm

https://github.com/ap/Proc-Fork
Perl | 282 lines | 43 code | 15 blank | 224 comment | 13 complexity | 4f8da93e9f9ae230ddcf9f1285e1c8ed MD5 | raw file
  1. use 5.006; use strict; use warnings;
  2. package Proc::Fork;
  3. our $VERSION = '0.806';
  4. use Exporter::Tidy (
  5. default => [ ':all' ],
  6. wrapper => [ 'run_fork' ],
  7. blocks => [ qw( parent child error retry ) ],
  8. );
  9. sub _croak { require Carp; goto &Carp::croak }
  10. my $do_clear = 1;
  11. my ( $parent, $child, $error, $retry );
  12. sub run_fork(&) {
  13. my $setup = shift;
  14. my @r = $setup->();
  15. _croak "Garbage in Proc::Fork setup (semicolon after last block clause?)" if @r;
  16. $do_clear = 1;
  17. my $pid;
  18. my $i;
  19. {
  20. $pid = fork;
  21. last if defined $pid;
  22. redo if $retry and $retry->( ++$i );
  23. die "Cannot fork: $!\n" if not $error;
  24. $error->();
  25. return;
  26. }
  27. $_->( $pid || () ) for ( $pid ? $parent : $child ) || ();
  28. return;
  29. }
  30. for my $block ( qw( parent child error retry ) ) {
  31. my $code = q{sub _BLOCK_ (&;@) {
  32. $parent = $child = $error = $retry = $do_clear = undef if $do_clear;
  33. _croak "Duplicate _BLOCK_ clause in Proc::Fork setup" if $_BLOCK_;
  34. $_BLOCK_ = shift if 'CODE' eq ref $_[0];
  35. _croak "Garbage in Proc::Fork setup (after _BLOCK_ clause)" if @_;
  36. run_fork {} if not defined wantarray; # backcompat
  37. ();
  38. }};
  39. $code =~ s/_BLOCK_/$block/g;
  40. eval $code;
  41. }
  42. 1;
  43. __END__
  44. =pod
  45. =encoding UTF-8
  46. =head1 NAME
  47. Proc::Fork - simple, intuitive interface to the fork() system call
  48. =head1 SYNOPSIS
  49. use Proc::Fork;
  50. run_fork {
  51. child {
  52. # child code goes here.
  53. }
  54. parent {
  55. my $child_pid = shift;
  56. # parent code goes here.
  57. waitpid $child_pid, 0;
  58. }
  59. retry {
  60. my $attempts = shift;
  61. # what to do if fork() fails:
  62. # return true to try again, false to abort
  63. return if $attempts > 5;
  64. sleep 1, return 1;
  65. }
  66. error {
  67. # Error-handling code goes here
  68. # (fork() failed and the retry block returned false)
  69. }
  70. };
  71. =head1 DESCRIPTION
  72. This module provides an intuitive, Perl-ish way to write forking programs by letting you use blocks to illustrate which code section executes in which fork. The code for the parent, child, retry handler and error handler are grouped together in a "fork block". The clauses may appear in any order, but they must be consecutive (without any other statements in between).
  73. All four clauses need not be specified. If the retry clause is omitted, only one fork will be attempted. If the error clause is omitted the program will die with a simple message if it can't retry. If the parent or child clause is omitted, the respective (parent or child) process will start execution after the final clause. So if one or the other only has to do some simple action, you need only specify that one. For example:
  74. # spawn off a child process to do some simple processing
  75. run_fork { child {
  76. exec '/bin/ls', '-l';
  77. die "Couldn't exec ls: $!\n";
  78. } };
  79. # Parent will continue execution from here
  80. # ...
  81. If the code in any of the clauses does not die or exit, it will continue execution after the fork block.
  82. =head1 INTERFACE
  83. All of the following functions are exported by default:
  84. =head2 run_fork
  85. run_fork { ... }
  86. Performs the fork operation configured in its block.
  87. =head2 child
  88. child { ... }
  89. Declares the block that should run in the child process.
  90. =head2 parent
  91. parent { ... }
  92. Declares the block that should run in the parent process. The child's PID is passed as an argument to the block.
  93. =head2 retry
  94. retry { ... }
  95. Declares the block that should run in case of an error, ie. if C<fork> returned C<undef>. If the code returns true, another C<fork> is attempted. The number of fork attempts so far is passed as an argument to the block.
  96. This can be used to implement a wait-and-retry logic that may be essential for some applications like daemons.
  97. If a C<retry> clause is not used, no retries will be attempted and a fork failure will immediately lead to the C<error> clause being called.
  98. =head2 error
  99. error { ... }
  100. Declares the block that should run if there was an error, ie when C<fork> returns C<undef> and the C<retry> clause returns false. The number of forks attempted is passed as an argument to the block.
  101. If an C<error> clause is not used, errors will raise an exception using C<die>.
  102. =head1 EXAMPLES
  103. =head2 Simple example with IPC via pipe
  104. =for eg simple.pl
  105. use strict;
  106. use Proc::Fork;
  107. use IO::Pipe;
  108. my $p = IO::Pipe->new;
  109. run_fork {
  110. parent {
  111. my $child = shift;
  112. $p->reader;
  113. print while <$p>;
  114. waitpid $child,0;
  115. }
  116. child {
  117. $p->writer;
  118. print $p "Line 1\n";
  119. print $p "Line 2\n";
  120. exit;
  121. }
  122. retry {
  123. if( $_[0] < 5 ) {
  124. sleep 1;
  125. return 1;
  126. }
  127. return 0;
  128. }
  129. error {
  130. die "That's all folks\n";
  131. }
  132. };
  133. =head2 Multi-child example
  134. =for eg multichild.pl
  135. use strict;
  136. use Proc::Fork;
  137. use IO::Pipe;
  138. my $num_children = 5; # How many children we'll create
  139. my @children; # Store connections to them
  140. $SIG{CHLD} = 'IGNORE'; # Don't worry about reaping zombies
  141. # Spawn off some children
  142. for my $num ( 1 .. $num_children ) {
  143. # Create a pipe for parent-child communication
  144. my $pipe = IO::Pipe->new;
  145. # Child simply echoes data it receives, until EOF
  146. run_fork { child {
  147. $pipe->reader;
  148. my $data;
  149. while ( $data = <$pipe> ) {
  150. chomp $data;
  151. print STDERR "child $num: [$data]\n";
  152. }
  153. exit;
  154. } };
  155. # Parent here
  156. $pipe->writer;
  157. push @children, $pipe;
  158. }
  159. # Send some data to the kids
  160. for ( 1 .. 20 ) {
  161. # pick a child at random
  162. my $num = int rand $num_children;
  163. my $child = $children[$num];
  164. print $child "Hey there.\n";
  165. }
  166. =head2 Daemon example
  167. =for eg daemon.pl
  168. use strict;
  169. use Proc::Fork;
  170. use POSIX;
  171. # One-stop shopping: fork, die on error, parent process exits.
  172. run_fork { parent { exit } };
  173. # Other daemon initialization activities.
  174. $SIG{INT} = $SIG{TERM} = $SIG{HUP} = $SIG{PIPE} = \&some_signal_handler;
  175. POSIX::setsid() == -1 and die "Cannot start a new session: $!\n";
  176. close $_ for *STDIN, *STDOUT, *STDERR;
  177. # rest of daemon program follows
  178. =head2 Forking socket-based network server example
  179. =for eg server.pl
  180. use strict;
  181. use IO::Socket::INET;
  182. use Proc::Fork;
  183. $SIG{CHLD} = 'IGNORE';
  184. my $server = IO::Socket::INET->new(
  185. LocalPort => 7111,
  186. Type => SOCK_STREAM,
  187. Reuse => 1,
  188. Listen => 10,
  189. ) or die "Couln't start server: $!\n";
  190. my $client;
  191. while ($client = $server->accept) {
  192. run_fork { child {
  193. # Service the socket
  194. sleep(10);
  195. print $client "Ooga! ", time % 1000, "\n";
  196. exit; # child exits. Parent loops to accept another connection.
  197. } }
  198. }
  199. =head1 AUTHOR
  200. Aristotle Pagaltzis <pagaltzis@gmx.de>
  201. Documentation by Eric J. Roode.
  202. =head1 COPYRIGHT AND LICENSE
  203. This documentation is copyright (c) 2002 by Eric J. Roode.
  204. =cut