1AnyEvent::Util(3) User Contributed Perl Documentation AnyEvent::Util(3)
2
3
4
6 AnyEvent::Util - various utility functions.
7
9 use AnyEvent::Util;
10
12 This module implements various utility functions, mostly replacing
13 well-known functions by event-ised counterparts.
14
15 All functions documented without "AnyEvent::Util::" prefix are exported
16 by default.
17
18 ($r, $w) = portable_pipe
19 Calling "pipe" in Perl is portable - except it doesn't really work
20 on sucky windows platforms (at least not with most perls - cygwin's
21 perl notably works fine): On windows, you actually get two file
22 handles you cannot use select on.
23
24 This function gives you a pipe that actually works even on the
25 broken windows platform (by creating a pair of TCP sockets on
26 windows, so do not expect any speed from that) and using "pipe"
27 everywhere else.
28
29 See "portable_socketpair", below, for a bidirectional "pipe".
30
31 Returns the empty list on any errors.
32
33 ($fh1, $fh2) = portable_socketpair
34 Just like "portable_pipe", above, but returns a bidirectional pipe
35 (usually by calling "socketpair" to create a local loopback socket
36 pair, except on windows, where it again returns two interconnected
37 TCP sockets).
38
39 Returns the empty list on any errors.
40
41 fork_call { CODE } @args, $cb->(@res)
42 Executes the given code block asynchronously, by forking.
43 Everything the block returns will be transferred to the calling
44 process (by serialising and deserialising via Storable).
45
46 If there are any errors, then the $cb will be called without any
47 arguments. In that case, either $@ contains the exception (and $!
48 is irrelevant), or $! contains an error number. In all other cases,
49 $@ will be "undef"ined.
50
51 The code block must not ever call an event-polling function or use
52 event-based programming that might cause any callbacks registered
53 in the parent to run.
54
55 Win32 spoilers: Due to the endlessly sucky and broken native
56 windows perls (there is no way to cleanly exit a child process on
57 that platform that doesn't also kill the parent), you have to make
58 sure that your main program doesn't exit as long as any
59 "fork_calls" are still in progress, otherwise the program won't
60 exit. Also, on most windows platforms some memory will leak for
61 every invocation. We are open for improvements that don't require
62 XS hackery.
63
64 Note that forking can be expensive in large programs (RSS 200MB+).
65 On windows, it is abysmally slow, do not expect more than 5..20
66 forks/s on that sucky platform (note this uses perl's pseudo-
67 threads, so avoid those like the plague).
68
69 Example: poor man's async disk I/O (better use AnyEvent::IO
70 together with IO::AIO).
71
72 fork_call {
73 open my $fh, "</etc/passwd"
74 or die "passwd: $!";
75 local $/;
76 <$fh>
77 } sub {
78 my ($passwd) = @_;
79 ...
80 };
81
82 $AnyEvent::Util::MAX_FORKS [default: 10]
83 The maximum number of child processes that "fork_call" will fork in
84 parallel. Any additional requests will be queued until a slot
85 becomes free again.
86
87 The environment variable "PERL_ANYEVENT_MAX_FORKS" is used to
88 initialise this value.
89
90 fh_nonblocking $fh, $nonblocking
91 Sets the blocking state of the given filehandle (true ==
92 nonblocking, false == blocking). Uses fcntl on anything sensible
93 and ioctl FIONBIO on broken (i.e. windows) platforms.
94
95 Instead of using this function, you could use "AnyEvent::fh_block"
96 or "AnyEvent::fh_unblock".
97
98 $guard = guard { CODE }
99 This function creates a special object that, when destroyed, will
100 execute the code block.
101
102 This is often handy in continuation-passing style code to clean up
103 some resource regardless of where you break out of a process.
104
105 The Guard module will be used to implement this function, if it is
106 available. Otherwise a pure-perl implementation is used.
107
108 While the code is allowed to throw exceptions in unusual
109 conditions, it is not defined whether this exception will be
110 reported (at the moment, the Guard module and AnyEvent's pure-perl
111 implementation both try to report the error and continue).
112
113 You can call one method on the returned object:
114
115 $guard->cancel
116 This simply causes the code block not to be invoked: it "cancels"
117 the guard.
118
119 AnyEvent::Util::close_all_fds_except @fds
120 This rarely-used function simply closes all file descriptors (or
121 tries to) of the current process except the ones given as
122 arguments.
123
124 When you want to start a long-running background server, then it is
125 often beneficial to do this, as too many C-libraries are too stupid
126 to mark their internal fd's as close-on-exec.
127
128 The function expects to be called shortly before an "exec" call.
129
130 Example: close all fds except 0, 1, 2.
131
132 close_all_fds_except 0, 2, 1;
133
134 $cv = run_cmd $cmd, key => value...
135 Run a given external command, potentially redirecting file
136 descriptors and return a condition variable that gets sent the exit
137 status (like $?) when the program exits and all redirected file
138 descriptors have been exhausted.
139
140 The $cmd is either a single string, which is then passed to a
141 shell, or an arrayref, which is passed to the "execvp" function
142 (the first array element is used both for the executable name and
143 argv[0]).
144
145 The key-value pairs can be:
146
147 ">" => $filename
148 Redirects program standard output into the specified filename,
149 similar to ">filename" in the shell.
150
151 ">" => \$data
152 Appends program standard output to the referenced scalar. The
153 condvar will not be signalled before EOF or an error is
154 signalled.
155
156 Specifying the same scalar in multiple ">" pairs is allowed,
157 e.g. to redirect both stdout and stderr into the same scalar:
158
159 ">" => \$output,
160 "2>" => \$output,
161
162 ">" => $filehandle
163 Redirects program standard output to the given filehandle (or
164 actually its underlying file descriptor).
165
166 ">" => $callback->($data)
167 Calls the given callback each time standard output receives
168 some data, passing it the data received. On EOF or error, the
169 callback will be invoked once without any arguments.
170
171 The condvar will not be signalled before EOF or an error is
172 signalled.
173
174 "fd>" => $see_above
175 Like ">", but redirects the specified fd number instead.
176
177 "<" => $see_above
178 The same, but redirects the program's standard input instead.
179 The same forms as for ">" are allowed.
180
181 In the callback form, the callback is supposed to return data
182 to be written, or the empty list or "undef" or a zero-length
183 scalar to signal EOF.
184
185 Similarly, either the write data must be exhausted or an error
186 is to be signalled before the condvar is signalled, for both
187 string-reference and callback forms.
188
189 "fd<" => $see_above
190 Like "<", but redirects the specified file descriptor instead.
191
192 on_prepare => $cb
193 Specify a callback that is executed just before the command is
194 "exec"'ed, in the child process. Be careful not to use any
195 event handling or other services not available in the child.
196
197 This can be useful to set up the environment in special ways,
198 such as changing the priority of the command or manipulating
199 signal handlers (e.g. setting "SIGINT" to "IGNORE").
200
201 close_all => $boolean
202 When "close_all" is enabled (default is disabled), then all
203 extra file descriptors will be closed, except the ones that
204 were redirected and 0, 1 and 2.
205
206 See "close_all_fds_except" for more details.
207
208 '$$' => \$pid
209 A reference to a scalar which will receive the PID of the
210 newly-created subprocess after "run_cmd" returns.
211
212 Note the the PID might already have been recycled and used by
213 an unrelated process at the time "run_cmd" returns, so it's not
214 useful to send signals, use as a unique key in data structures
215 and so on.
216
217 Example: run "rm -rf /", redirecting standard input, output and
218 error to /dev/null.
219
220 my $cv = run_cmd [qw(rm -rf /)],
221 "<", "/dev/null",
222 ">", "/dev/null",
223 "2>", "/dev/null";
224 $cv->recv and die "d'oh! something survived!"
225
226 Example: run openssl and create a self-signed certificate and key,
227 storing them in $cert and $key. When finished, check the exit
228 status in the callback and print key and certificate.
229
230 my $cv = run_cmd [qw(openssl req
231 -new -nodes -x509 -days 3650
232 -newkey rsa:2048 -keyout /dev/fd/3
233 -batch -subj /CN=AnyEvent
234 )],
235 "<", "/dev/null",
236 ">" , \my $cert,
237 "3>", \my $key,
238 "2>", "/dev/null";
239
240 $cv->cb (sub {
241 shift->recv and die "openssl failed";
242
243 print "$key\n$cert\n";
244 });
245
246 AnyEvent::Util::punycode_encode $string
247 Punycode-encodes the given $string and returns its punycode form.
248 Note that uppercase letters are not casefolded - you have to do
249 that yourself.
250
251 Croaks when it cannot encode the string.
252
253 AnyEvent::Util::punycode_decode $string
254 Tries to punycode-decode the given $string and return its unicode
255 form. Again, uppercase letters are not casefoled, you have to do
256 that yourself.
257
258 Croaks when it cannot decode the string.
259
260 AnyEvent::Util::idn_nameprep $idn[, $display]
261 Implements the IDNA nameprep normalisation algorithm. Or actually
262 the UTS#46 algorithm. Or maybe something similar - reality is
263 complicated between IDNA2003, UTS#46 and IDNA2008. If $display is
264 true then the name is prepared for display, otherwise it is
265 prepared for lookup (default).
266
267 If you have no clue what this means, look at "idn_to_ascii"
268 instead.
269
270 This function is designed to avoid using a lot of resources - it
271 uses about 1MB of RAM (most of this due to Unicode::Normalize).
272 Also, names that are already "simple" will only be checked for
273 basic validity, without the overhead of full nameprep processing.
274
275 $domainname = AnyEvent::Util::idn_to_ascii $idn
276 Converts the given unicode string ($idn, international domain name,
277 e.g. 日本語。JP) to a pure-ASCII domain name (this is usually
278 called the "IDN ToAscii" transform). This transformation is
279 idempotent, which means you can call it just in case and it will do
280 the right thing.
281
282 Unlike some other "ToAscii" implementations, this one works on full
283 domain names and should never fail - if it cannot convert the name,
284 then it will return it unchanged.
285
286 This function is an amalgam of IDNA2003, UTS#46 and IDNA2008 - it
287 tries to be reasonably compatible to other implementations,
288 reasonably secure, as much as IDNs can be secure, and reasonably
289 efficient when confronted with IDNs that are already valid DNS
290 names.
291
292 $idn = AnyEvent::Util::idn_to_unicode $idn
293 Converts the given unicode string ($idn, international domain name,
294 e.g. 日本語。JP, www.deliantra.net, www.xn--l-0ga.de) to unicode
295 form (this is usually called the "IDN ToUnicode" transform). This
296 transformation is idempotent, which means you can call it just in
297 case and it will do the right thing.
298
299 Unlike some other "ToUnicode" implementations, this one works on
300 full domain names and should never fail - if it cannot convert the
301 name, then it will return it unchanged.
302
303 This function is an amalgam of IDNA2003, UTS#46 and IDNA2008 - it
304 tries to be reasonably compatible to other implementations,
305 reasonably secure, as much as IDNs can be secure, and reasonably
306 efficient when confronted with IDNs that are already valid DNS
307 names.
308
309 At the moment, this function simply calls "idn_nameprep $idn, 1",
310 returning its argument when that function fails.
311
313 Marc Lehmann <schmorp@schmorp.de>
314 http://anyevent.schmorp.de
315
316
317
318perl v5.32.1 2021-01-26 AnyEvent::Util(3)