| 1 |
root |
1.1 |
=head1 NAME |
| 2 |
|
|
|
| 3 |
|
|
Coro::Util - various utility functions. |
| 4 |
|
|
|
| 5 |
|
|
=head1 SYNOPSIS |
| 6 |
|
|
|
| 7 |
|
|
use Coro::Util; |
| 8 |
|
|
|
| 9 |
|
|
=head1 DESCRIPTION |
| 10 |
|
|
|
| 11 |
|
|
This module implements various utility functions, mostly replacing perl |
| 12 |
|
|
functions by non-blocking counterparts. |
| 13 |
|
|
|
| 14 |
|
|
=over 4 |
| 15 |
|
|
|
| 16 |
|
|
=cut |
| 17 |
|
|
|
| 18 |
|
|
package Coro::Util; |
| 19 |
|
|
|
| 20 |
pcg |
1.10 |
BEGIN { eval { require warnings } && warnings->unimport ("uninitialized") } |
| 21 |
root |
1.2 |
|
| 22 |
root |
1.1 |
#use Carp qw(croak); |
| 23 |
|
|
|
| 24 |
|
|
use Coro::Handle; |
| 25 |
|
|
use Coro::Semaphore; |
| 26 |
|
|
|
| 27 |
|
|
use base 'Exporter'; |
| 28 |
|
|
|
| 29 |
|
|
@EXPORT = qw( |
| 30 |
|
|
gethostbyname gethostbyaddr |
| 31 |
|
|
); |
| 32 |
|
|
|
| 33 |
pcg |
1.12 |
$VERSION = 0.95; |
| 34 |
root |
1.1 |
|
| 35 |
|
|
$MAXPARALLEL = 16; # max. number of parallel jobs |
| 36 |
|
|
|
| 37 |
|
|
my $jobs = new Coro::Semaphore $MAXPARALLEL; |
| 38 |
|
|
|
| 39 |
|
|
sub _do_asy(&;@) { |
| 40 |
|
|
require POSIX; # just for _exit |
| 41 |
|
|
|
| 42 |
|
|
my $sub = shift; |
| 43 |
|
|
$jobs->down; |
| 44 |
|
|
my $fh; |
| 45 |
|
|
if (0 == open $fh, "-|") { |
| 46 |
|
|
syswrite STDOUT, join "\0", map { unpack "H*", $_ } &$sub; |
| 47 |
|
|
POSIX::_exit(0); |
| 48 |
|
|
} |
| 49 |
|
|
my $buf; |
| 50 |
|
|
$fh = unblock $fh; |
| 51 |
root |
1.2 |
$fh->sysread($buf, 16384); |
| 52 |
root |
1.1 |
close $fh; |
| 53 |
|
|
$jobs->up; |
| 54 |
|
|
my @r = map { pack "H*", $_ } split /\0/, $buf; |
| 55 |
|
|
wantarray ? @r : $r[0]; |
| 56 |
|
|
} |
| 57 |
|
|
|
| 58 |
|
|
=item gethostbyname, gethostbyaddr |
| 59 |
|
|
|
| 60 |
|
|
Work exactly like their perl counterparts, but do not block. Currently |
| 61 |
|
|
this is being implemented by forking, so it's not exactly low-cost. |
| 62 |
|
|
|
| 63 |
|
|
=cut |
| 64 |
|
|
|
| 65 |
root |
1.5 |
my $netdns = eval { require Net::DNS::Resolver; new Net::DNS::Resolver; 0 }; |
| 66 |
root |
1.4 |
|
| 67 |
root |
1.1 |
sub gethostbyname($) { |
| 68 |
root |
1.4 |
if ($netdns) { |
| 69 |
root |
1.5 |
#$netdns->query($_[0]); |
| 70 |
root |
1.4 |
die; |
| 71 |
|
|
} else { |
| 72 |
|
|
_do_asy { gethostbyname $_[0] } @_; |
| 73 |
|
|
} |
| 74 |
root |
1.1 |
} |
| 75 |
|
|
|
| 76 |
|
|
sub gethostbyaddr($$) { |
| 77 |
root |
1.4 |
if ($netdns) { |
| 78 |
|
|
die; |
| 79 |
|
|
} else { |
| 80 |
|
|
_do_asy { gethostbyaddr $_[0], $_[1] } @_; |
| 81 |
|
|
} |
| 82 |
root |
1.1 |
} |
| 83 |
|
|
|
| 84 |
|
|
1; |
| 85 |
|
|
|
| 86 |
|
|
=head1 AUTHOR |
| 87 |
|
|
|
| 88 |
|
|
Marc Lehmann <pcg@goof.com> |
| 89 |
|
|
http://www.goof.com/pcg/marc/ |
| 90 |
|
|
|
| 91 |
|
|
=cut |
| 92 |
|
|
|