1 |
package AnyEvent::Fork::RPC::Sync; |
2 |
|
3 |
use common::sense; # actually required to avoid spurious warnings... |
4 |
|
5 |
# declare only |
6 |
sub AnyEvent::Fork::RPC::event; |
7 |
|
8 |
sub do_exit { exit } # workaround for perl 5.14 and below |
9 |
|
10 |
# the goal here is to keep this simple, small and efficient |
11 |
sub run { |
12 |
my ($function, $init, $serialiser, undef) = splice @_, -4, 4; |
13 |
my $rfh = shift; |
14 |
my $wfh = fileno $rfh ? $rfh : *STDOUT; |
15 |
|
16 |
$0 =~ s/^AnyEvent::Fork::RPC::Sync::run of /$function of /; |
17 |
|
18 |
{ |
19 |
package main; |
20 |
&$init if length $init; |
21 |
$function = \&$function; # resolve function early for extra speed |
22 |
} |
23 |
|
24 |
my ($f, $t) = eval $serialiser; die $@ if $@; |
25 |
|
26 |
my $write = sub { |
27 |
my $got = syswrite $wfh, $_[0]; |
28 |
|
29 |
while ($got < length $_[0]) { |
30 |
my $len = syswrite $wfh, $_[0], 1<<30, $got; |
31 |
|
32 |
defined $len |
33 |
or die "AnyEvent::Fork::RPC::Sync: write error ($!), parent gone?"; |
34 |
|
35 |
$got += $len; |
36 |
} |
37 |
}; |
38 |
|
39 |
*AnyEvent::Fork::RPC::event = sub { |
40 |
$write->(pack "NN/a*", 0, &$f); |
41 |
}; |
42 |
|
43 |
my ($rlen, $rbuf) = 512 - 16; |
44 |
|
45 |
while (sysread $rfh, $rbuf, $rlen - length $rbuf, length $rbuf) { |
46 |
$rlen = $rlen * 2 + 16 if $rlen - 128 < length $rbuf; |
47 |
|
48 |
while () { |
49 |
last if 4 > length $rbuf; |
50 |
my $len = unpack "N", $rbuf; |
51 |
last if 4 + $len > length $rbuf; |
52 |
|
53 |
$write->(pack "NN/a*", 1, $f->($function->($t->(substr $rbuf, 4, $len)))); |
54 |
|
55 |
substr $rbuf, 0, 4 + $len, ""; |
56 |
} |
57 |
} |
58 |
|
59 |
shutdown $wfh, 1; |
60 |
exit; # work around broken win32 perls |
61 |
} |
62 |
|
63 |
1 |
64 |
|