| 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 |
# the goal here is to keep this simple, small and efficient |
| 9 |
sub run { |
| 10 |
my ($function, $init, $serialiser) = splice @_, -3, 3,; |
| 11 |
my $master = shift; |
| 12 |
|
| 13 |
{ |
| 14 |
package main; |
| 15 |
&$init if length $init; |
| 16 |
$function = \&$function; # resolve function early for extra speed |
| 17 |
} |
| 18 |
|
| 19 |
my ($f, $t) = eval $serialiser; die $@ if $@; |
| 20 |
|
| 21 |
my $write = sub { |
| 22 |
my $got = syswrite $master, $_[0]; |
| 23 |
|
| 24 |
while ($got < length $_[0]) { |
| 25 |
my $len = syswrite $master, $_[0], 1<<30, $got; |
| 26 |
|
| 27 |
defined $len |
| 28 |
or die "AnyEvent::Fork::RPC::Sync: write error ($!), parent gone?"; |
| 29 |
|
| 30 |
$got += $len; |
| 31 |
} |
| 32 |
}; |
| 33 |
|
| 34 |
*AnyEvent::Fork::RPC::event = sub { |
| 35 |
$write->(pack "LL/a*", 0, &$f); |
| 36 |
}; |
| 37 |
|
| 38 |
my ($rlen, $rbuf) = 512 - 16; |
| 39 |
|
| 40 |
while (sysread $master, $rbuf, $rlen - length $rbuf, length $rbuf) { |
| 41 |
$rlen = $rlen * 2 + 16 if $rlen - 128 < length $rbuf; |
| 42 |
|
| 43 |
while () { |
| 44 |
last if 4 > length $rbuf; |
| 45 |
my $len = unpack "L", $rbuf; |
| 46 |
last if 4 + $len > length $rbuf; |
| 47 |
|
| 48 |
$write->(pack "LL/a*", 1, $f->($function->($t->(substr $rbuf, 4, $len)))); |
| 49 |
|
| 50 |
substr $rbuf, 0, 4 + $len, ""; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
shutdown $master, 1; |
| 55 |
} |
| 56 |
|
| 57 |
1 |
| 58 |
|