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 |
root |
1.3 |
no warnings qw(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 |
root |
1.4 |
$VERSION = 0.6; |
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.4 |
my $netdns = 0 && eval { use Net::DNS 0.24 }; |
66 |
|
|
|
67 |
root |
1.1 |
sub gethostbyname($) { |
68 |
root |
1.4 |
if ($netdns) { |
69 |
|
|
die; |
70 |
|
|
} else { |
71 |
|
|
_do_asy { gethostbyname $_[0] } @_; |
72 |
|
|
} |
73 |
root |
1.1 |
} |
74 |
|
|
|
75 |
|
|
sub gethostbyaddr($$) { |
76 |
root |
1.4 |
if ($netdns) { |
77 |
|
|
die; |
78 |
|
|
} else { |
79 |
|
|
_do_asy { gethostbyaddr $_[0], $_[1] } @_; |
80 |
|
|
} |
81 |
root |
1.1 |
} |
82 |
|
|
|
83 |
|
|
1; |
84 |
|
|
|
85 |
|
|
=head1 AUTHOR |
86 |
|
|
|
87 |
|
|
Marc Lehmann <pcg@goof.com> |
88 |
|
|
http://www.goof.com/pcg/marc/ |
89 |
|
|
|
90 |
|
|
=cut |
91 |
|
|
|