1Event::Lib(3) User Contributed Perl Documentation Event::Lib(3)
2
3
4
6 Event::Lib - Perl extentions for event-based programming
7
9 use Event::Lib;
10 use POSIX qw/SIGINT/;
11
12 my $seconds;
13 sub timer {
14 my $event = shift;
15 print "\r", ++$seconds;
16 $event->add(1);
17 }
18
19 sub reader {
20 my $event = shift;
21 my $fh = $event->fh;
22 print <$fh>;
23 $event->add;
24 }
25
26 sub signal {
27 my $event = shift;
28 print "Caught SIGINT\n";
29 }
30
31 my $timer = timer_new(\&timer);
32 my $reader = event_new(\*STDIN, EV_READ, \&reader);
33 my $signal = signal_new(SIGINT, \&signal);
34
35 $timer->add(1); # triggered every second
36 $reader->add;
37 $signal->add;
38
39 event_mainloop;
40
42 This module is a Perl wrapper around libevent(3) as available from
43 <http://www.monkey.org/~provos/libevent/>. It allows to execute a
44 function whenever a given event on a filehandle happens, a timeout
45 occurs or a signal is received.
46
47 Under the hood, one of the available mechanisms for asynchronously
48 dealing with events is used. This could be "select", "poll", "epoll",
49 "devpoll" or "kqueue". The idea is that you don't have to worry about
50 those details and the various interfaces they offer. Event::Lib offers
51 a unified interface to all of them (but see "CONFIGURATION" further
52 below).
53
54 Once you've skimmed through the next two sections (or maybe even now),
55 you should have a look at "EXAMPLE: A SIMPLE TCP SERVER" to get a
56 feeling about how it all fits together.
57
58 There's also a section briefly mentioning other event modules on the
59 CPAN and how they differ from Event::Lib further below ("OTHER EVENT
60 MODULES").
61
63 This happens via loading the module via use() or require():
64
65 use Event::Lib;
66
67 No further work is ever required.
68
69 Additionally, you may use the following two functions to retrieve some
70 information regarding the underlying libevent. These functions are
71 neither exported nor exportable so you have to call them fully package-
72 qualified:
73
74 * Event::Lib::get_version()
75 This returns the version of libevent this module was compiled against.
76
77 * Event::Lib::get_method()
78 This returns the kernel notification method used by libevent. This will
79 be one of "select", "poll", "epoll", "devpoll" and "kqueue".
80
82 The standard procedure is to create a few events and afterwards enter
83 the loop (using event_mainloop()) to wait for and handle the pending
84 events. This loop is truely global and shared even between forked
85 processes. The same is true for events that you register. They will all
86 be processed by the same loop, no matter where or how you create them.
87
88 Each event has a Perl function associated with itself that gets
89 triggered when the event is due. Further event handling is delayed
90 until the currently executing event handler is done. If you want an
91 event to be handled as soon as it becomes imminent, it has to run in
92 its own process so that it cannot be disturbed by other event handlers.
93 This is particularly important for timer-based events when you expect
94 those events to fire steadily every few seconds.
95
96 There's one more little thing to be aware of: Sometimes it may apear
97 that your events aren't triggered because they produce no output in
98 spite of your precious print() statements you put in. If you see no
99 output, then you're a victim of buffering. The solution is to turn on
100 autoflushing, so put
101
102 $| = 1;
103
104 at the top of your program if no output appears on your screen or
105 filehandles.
106
107 Event::Lib knows three different kind of events: a filehandle becomes
108 readable/writeable, timeouts and signals.
109
111 Most often you will have a set of filehandles that you want to watch
112 and handle simultaneously. Think of a webserver handling multiple
113 client requests. Such an event is created with event_new():
114
115 * event_new($fh, $flags, $function, [@args])
116 $fh is the filehandle you want to watch. $flags may be the bit-wise
117 ORing of "EV_READ", "EV_WRITE" and "EV_PERSIST". "EV_PERSIST" will make
118 the event persistent, that is: Once the event is triggered, it is not
119 removed from the event-loop. If you do not pass this flag, you have to
120 re-schedule the event in the event-handler $function.
121
122 $function is the callback that is executed when the given event
123 happened. This function is always called with at least two arguments,
124 namely the event object itself which was created by the above
125 event_new() and an integer being the event-type that occured (which
126 could be "EV_WRITE", "EV_READ" or "EV_TIMEOUT"). @args is an optional
127 list of additional arguments your callback will receive.
128
129 NOTE: $fh really ought to be a socket or a pipe. Regular files can't be
130 handled by at least epoll(2). If, for some reason, you want to put an
131 event on a regular file, you have to make sure that a kernel
132 notification method is used that can deal with such file-handles.
133 select(2) and poll(2) are good candidates as they don't have this
134 limitation. So in order to prevent this limitation, you have to do:
135
136 BEGIN {
137 $ENV{ $_ } = 1 for qw/EVENT_NOEPOLL EVENT_NODEVPOLL EVENT_NOKQUEUE/;
138 }
139 use Event::Lib;
140
141 See "CONFIGURATION" further below for more details.
142
143 The function returns an event object (the very object that is later
144 passed to the callback function).
145
146 Here's an example how to create a listening socket that can accept
147 connections from multiple clients:
148
149 use IO::Socket::INET;
150 use Event::Lib;
151
152 sub accept_connection {
153 my $event = shift;
154 my $sock = $event->fh;
155 my $client = $sock->accept;
156 ...
157 }
158
159 my $server = IO::Socket::INET->new(
160 LocalAddr => 'localhost',
161 LocalPort => 9000,
162 Proto => 'tcp',
163 ReuseAddr => SO_REUSEADDR,
164 Listen => 1,
165 Blocking => 0,
166 ) or die $@;
167
168 my $main = event_new($server, EV_READ|EV_PERSIST, \&accept_connection);
169
170 # add the event to the event loop
171 $main->add;
172
173 event_mainloop();
174
175 The above can be done without the "EV_PERSIST" flag as well:
176
177 sub accept_connection {
178 my $event = shift;
179 my $sock = $event->fh;
180 my $client = $sock->accept;
181 ...
182 # re-schedule event
183 $event->add;
184 }
185 ...
186 my $main = event_new($server, EV_READ, \&accept_connection);
187 $main->add;
188 event_mainloop();
189
190 * $event->add( [$timeout] )
191 Alias: event_add( $event, [$timeout] )
192
193 This adds the event previously created with event_new() to the event-
194 loop. $timeout is an optional argument specifying a timeout given as
195 floating-point number. It means that the event handler is triggered
196 either when the event happens or when $timeout seconds have passed,
197 whichever comes first.
198
199 Consider this snippet:
200
201 use Event::Lib;
202
203 sub handler {
204 my ($ev, $type) = @_;
205 if ($type == EV_READ) {
206 ...
207 }
208 elsif ($type == EV_TIMEOUT) {
209 ...
210 }
211 }
212
213 # wait at most for 1.5 seconds
214 event_new(\*STDIN, EV_READ, \&handler)->add(1.5);
215 event_one_loop;
216
217 If "STDIN" becomes readable within 1.5 seconds, handler() will be
218 called with $type set to "EV_READ". If nothing happens within these 1.5
219 seconds, it'll be called with $type set to "EV_TIMEOUT".
220
221 When $timeout is 0 it behaves as if no timeout has been given, that is:
222 An infinite timeout is assumed. Any other timeout is taken literally,
223 so 0.0 is not the same! In such a case, the event handler will be
224 called immediately with the event type set to "EV_TIMEOUT".
225
226 It's a fatal error to add the same event multiple times:
227
228 my $e = event_new(...);
229 $e->add;
230 $e->add; # this line will die
231
232 When an event couldn't be added for some other reason, the event's
233 exception handler is called. See "EXCEPTION HANDLING" further below on
234 how exceptions raised by event_add() differ from other exceptions.
235
236 * $event->fh
237 Returns the filehandle this $event is supposed to watch. You will
238 usually call this in the event-handler.
239
240 * $event->remove
241 This removes an event object from the event-loop. Note that the object
242 itself is not destroyed and freed. It is merely disabled and you can
243 later re-enable it by calling "$event->add".
244
246 Sometimes you want events to happen periodically, regardless of any
247 filehandles. Such events are created with timer_new():
248
249 * timer_new( $function, [@args] )
250 This is very much the same as event_new(), only that it lacks its first
251 two parameters. $function is a reference to a Perl function that
252 should be executed. As always, this function will receive the event
253 object as returned by timer_new() as first argument, the type of event
254 (always EV_TIMEOUT) plus the optional argumentlist @args.
255
256 * $event->add( [$timeout] )
257 Alias: event_add( $event, [$timeout] )
258
259 Adds $event to the event-loop. The event is scheduled to be triggered
260 every $timeout seconds where $timeout can be any floating-point value.
261 If $timeout is omitted, a value of one second is assumed.
262
263 It will throw an exception if adding the given event failed. If you
264 still want your program to keep running, wrap this statement into an
265 eval block:
266
267 my $e = event_new(...);
268 eval {
269 $e->add;
270 } or warn "Adding failed";
271
272 Note that timer-based events are not persistent so you have to call
273 this method/function again in the event-handler in order to re-schedule
274 it.
275
276 It's a fatal error to add the same event multiple times:
277
278 my $e = timer_new(...);
279 $e->add;
280 $e->add; # this line will die
281
282 When an event couldn't be added for some other reason, the event's
283 exception handler is called. See "EXCEPTION HANDLING" further below on
284 how exceptions raised by event_add() differ from other exceptions.
285
286 * $event->remove
287 This removes the timer-event $event from the event-loop. Again, $event
288 remains intact and may later be re-scheduled with event_add().
289
291 Your program can also respond to signals sent to it by other
292 applications. To handle signals, you create the corresponding event
293 using signal_new().
294
295 Note that thusly created events take precedence over event-handlers
296 defined in %SIG. That means the function you assigned to $SIG{ $SIGNAME
297 } will never be executed if a "Event::Lib"-handler for $SIGNAME also
298 exists.
299
300 * signal_new( $signal, $function, [@args] )
301 Sets up $function as a handler for $signal. $signal has to be an
302 integer specifying which signal to intercept and handle. For example,
303 15 is "SIGTERM" (on most platforms, anyway). You are advised to use the
304 symbolic names as exported by the POSIX module:
305
306 use Event::Lib;
307 use POSIX qw/SIGINT/;
308
309 my $signal = signal_new(SIGINT, sub { print "Someone hit ctrl-c" });
310 $signal->add;
311 event_mainloop();
312
313 As always, $function receives the event object as first argument, the
314 event-type (always EV_SIGNAL) as second. @args specifies an option list
315 of values that is to be passed to the handler.
316
317 * $event->add( [$timeout] )
318 Alias: event_add( $event, [$timeout] )
319
320 Adds the signal-event previously created with signal_new() to the
321 event-loop. $timeout is an optional argument specifying a timeout
322 given as floating-point number. It means that the event handler is
323 triggered either when the event happens or when $timeout seconds have
324 passed, whichever comes first.
325
326 $timeout here has the exact same semantics as with filehandle-based
327 events described further above.
328
329 Note that signal-events are always persistent unless $timeout was
330 given. That means that you have to delete the event manually if you
331 want it to happen only once:
332
333 sub sigint {
334 my $event = shift;
335 print "Someone hit ctrl-c";
336 $event->remove;
337 }
338
339 my $signal = signal_new(SIGINT, \&sigint);
340 $signal->add;
341 event_mainloop();
342
343 Subsequently, a persistent and timeouted signal-handler would read
344 thusly:
345
346 sub sigint {
347 my $event = shift;
348 print "Someone hit ctrl-c";
349 $event->add(2.5);
350 }
351
352 my $signal = signal_new(SIGINT, \&sigint);
353 $signal->add(2.5);
354 event_mainloop();
355
356 It's a fatal error to add the same event multiple times:
357
358 my $e = signal_new(...);
359 $e->add;
360 $e->add; # this line will die
361
362 When an event couldn't be added for some other reason, the event's
363 exception handler is called. See "EXCEPTION HANDLING" further below on
364 how exceptions raised by event_add() differ from other exceptions.
365
366 * $event->remove
367 The same as their counterparts for filehandle-events, so please see
368 above.
369
371 * $event->pending
372 This will tell you whether $event is still in the event-queue waiting
373 to be processed. More specifically, it returns a false value if $event
374 was already handled (and was not either persistent or re-scheduled). In
375 case $event is still in the queue it returns the amount of seconds as a
376 floating-point number until it is triggered again. If $event has no
377 attached timeout, it returns "0 but true".
378
379 * $event->args( [@args] )
380 When called with no arguments, it will in scalar context return the
381 number of additional arguments associated with $event. In list context,
382 it returns those arguments as one list.
383
384 When @args is given, the current list of arguments for $event is
385 replaced with @args and nothing is returned.
386
387 * $event->args_del
388 This will remove all additional arguments from $event so the next time
389 the event handler is called, the list of additional arguments passed to
390 it will be empty.
391
392 * $event->callback
393 Returns the callback associated with this event as code-reference so
394 that you can call it manually in case you think you need that:
395
396 $event->callback->($event, $event->fh, @args);
397
398 * $event->except_handler( $function )
399 You can associate an exception handler with each event which gets
400 called in case the callback for that event dies. $function is a Perl
401 code-reference which will - when called - receive the event as first
402 argument, the error message with which the event handler died, the type
403 of event and any additional arguments associated with that event. That
404 way you can inspect the circumstances and provide your own error-
405 handling.
406
407 Please see "EXCEPTION HANDLING" for some background and more details.
408
410 Event::Lib offers three functions to process pending events.
411
412 * event_mainloop ()
413 This function will start the event-loop and never return, generally.
414 More precisely, it will return if either the program ran out of events
415 in which case event_mainloop() returns a true value. In case of an
416 error during event-processing, it will return a false value in which
417 case you should check $!.
418
419 IMPORTANT: When any of your events register new events they will be
420 added to the global queue of events and be handled in the same loop.
421 You are therefore not allowed to call event_mainloop() more than once
422 in your program. Attempting to do so will yield a warning and the
423 operation is silently turned into a no-op.
424
425 * event_one_loop( [$timeout] )
426 This function will do exactly one loop which means the next pending
427 event is handled. In case no event is currently ready for processing,
428 it will block and wait until one becomes processible.
429
430 If $timeout is specified, it will wait at most $timeout seconds and
431 then return.
432
433 * event_one_nbloop ()
434 This is the non-blocking counterpart to event_one_loop(): It returns
435 immediately when no event is ready to be processed. Otherwise the next
436 imminent event is handled.
437
438 You want to use either event_one_loop() or event_one_nbloop() instead
439 of event_mainloop() if you want to write your own event-loop. The core
440 of such a program could look like this:
441
442 event_new(...)->add;
443 event_new(...)->add;
444 timer_new(...)->add;
445 ...
446
447 while () {
448 event_one_nbloop();
449 ...
450 select undef, undef, undef, 0.05; # sleep for 0.05 seconds
451 }
452
454 It is important to understand the lifetime of events because concepts
455 such as scope and visibility have little meaning with respect to
456 events.
457
458 When you add an event to the queue using event_add(), this event will
459 remain there until it is triggered, no matter what you do with the
460 object returned by event_new(), timer_new() and signal_new()
461 respectively. Consider this code:
462
463 use Event::Lib;
464 $| = 1;
465
466 my $event = timer_new(sub { print "timer called\n" });
467
468 # schedule the timer to go off in ten seconds
469 $event->add(10);
470
471 undef $event;
472 event_mainloop;
473
474 This program will, regardless of the "undef $event", print "timer
475 called". As a consequence, there is only one true and correct way to
476 cancel an event, namely by calling remove() on it. Likewise:
477
478 use warnings;
479 use Event::Lib;
480 $| = 1;
481
482 my $event = timer_new(sub { print "Called after two seconds\n" });
483 $event->add(2);
484 $event = timer_new(sub { print "Called after three seconds\n" });
485 $event->add(3);
486
487 event_mainloop;
488
489 __END__
490 Explicit undef() of or reassignment to pending event at - line 8.
491 Called after two seconds
492 Called after three seconds
493
494 So even though you have only one Perl object container $event, you have
495 two events!
496
497 As this can become hard to maintain in complex programs, Event::Lib
498 will emmit a warning if any of the above cases is detected and if you
499 have warnings enabled. If you don't want this warning turn it off
500 temporarily. The above program then becomes:
501
502 use warnings;
503 use Event::Lib;
504 $| = 1;
505
506 my $event = timer_new(sub { print "Called after two seconds\n" });
507 $event->add(2);
508
509 {
510 no warnings 'misc';
511 $event = timer_new(sub { print "Called after three seconds\n" });
512 $event->add(3);
513 }
514
515 event_mainloop;
516
517 Note that the line following the undef() or the reassignment has to be
518 within the "no warnings 'misc'"-block because this is the line where
519 this warning is actually triggered and not the line with the undef() or
520 reassignment itself.
521
523 Some programs simply cannot afford to die. It is a possible that a
524 callback is triggered and finds itself in a situation where it just
525 cannot proceed. Think of a callback that is supposed to append to a
526 file and in the meantime the disk has filled so that no space is left
527 on the device.
528
529 It is now possible to provide exception handlers for these cases. The
530 idea is that these exception handlers are called with the same
531 arguments the callback was previously triggered with (plus the error
532 message as second argument) which gives you the change to further
533 investigate the cause of the failure and possibly take counter-
534 measures.
535
536 You can register exception handlers per event using the
537 except_handler() method. Furthermore, you can register one global
538 exception handler that is going to be used for all events that don't
539 have their own handler:
540
541 * event_register_except_handler( $function )
542 $function is a code-reference that will be called whenever the callback
543 of an event dies:
544
545 use Event::Lib;
546
547 sub handler {
548 my ($event, $exception, $type, @args) = @_;
549 # error handling here
550 ...
551 }
552
553 event_register_except_handler(\&handler);
554 ...
555
556 If you don't call event_register_except_handler() Event::Lib will use
557 its own basic default handler. This handler simply dies with the
558 original error message.
559
560 Exceptions raised by event_add()
561 If the exception was raised by event_add(), then the event's exception
562 handler is called. This is either the one registered with
563 except_handler() on a per-event basis, the global one set via
564 event_register_except_handler() or, if both of these was not done, the
565 default handler.
566
567 In any case, the exception handler called from event_add() is called
568 with slightly different arguments. This is in order to allow the
569 handler to distinguish between the case where an exception was raised
570 by an event-handler or where it was raised by event_add().
571
572 The first two arguments being the event in question and the error
573 message are the same for both kind of exceptions. What differs is the
574 third argument, $type. It will always be negative when event_add()
575 triggered this exception.
576
577 In particular, the type of event $type will be for a...
578
579 ... filehandle-event:
580 The negated type-flags with which the event was created. This means
581 that for the following exception-handler and when "$e->add" failed:
582
583 sub exception_handler {
584 my ($e, $err, $evtype, @args) = @_;
585
586 # ref($e) eq "Event::Lib::event"
587 # $err =~ /^Couldn't add event at/
588 # $evtype == -(EV_READ|EV_PERSIST)
589 # @args == (1, 2, 3)
590 # $! will contain the OS-level error
591 }
592
593 my $e = event_new(\*FH, EV_READ|EV_PERSIST, \&handler, 1 .. 3);
594 ...
595 $e->add;
596
597 ... timer-event:
598 $type will be -EV_TIMEOUT:
599
600 sub exception_handler {
601 my ($e, $err, $evtype, @args) = @_;
602
603 # ref($e) eq "Event::Lib::timer"
604 # $err =~ /^Couldn't add event at/
605 # $evtype == -EV_TIMEOUT
606 # @args == (1, 2, 3)
607 }
608
609 my $e = timer_new(\&handler, 1 .. 3);
610 ...
611 $e->add;
612
613 ... signal-event:
614 $type will be the negated signal number this event was supposed to
615 handle:
616
617 sub exception_handler {
618 my ($e, $err, $evtype, @args);
619
620 # ref($e) eq "Event::Lib::signal"
621 # $err =~ /^Couldn't add event at/
622 # $evtype == -SIGTERM
623 # @args == (1, 2, 3)
624 }
625
626 my $e = signal_new(SIGTERM, \&handler, 1 .. 3);
627 ...
628 $e->add;
629
630 As a consequence, first have your exception-handler test the sign of
631 $evtype. If it was negative, use "ref($e)" to extract the kind of
632 event.
633
635 Events can be assigned a priority. The lower its assigned priority is,
636 the earlier this event is processed. Using prioritized events in your
637 programs requires two steps. The first one is to set the number of
638 available priorities. Setting those should happen once in your script
639 and before calling event_mainloop():
640
641 * event_priority_init( $priorities )
642 Sets the number of different events to $priorities.
643
644 Assigning a priority to each event then happens thusly:
645
646 * $event->set_priority( $priority )
647 Gives $event (which can be any of the three type of events) the
648 priority $priority. Remember that a lower priority means the event is
649 processed earlier!
650
651 Note: If your installed version of libevent does not yet contain
652 priorities which happens for pre-1.0 versions, the above will become
653 no-ops. Other than that, your scripts will remain functional.
654
656 There are some functions that will aid you in finding problems in your
657 program or even to assure you that your program is ok but there might
658 be a bug in Event::Lib.
659
660 * event_log_level( $loglevel )
661 You can specify what kind of messages Event::Lib should dump to stderr
662 by using thid function.
663
664 $loglevel is one of _EVENT_LOG_DEBUG, _EVENT_LOG_MSG, _EVENT_LOG_WARN,
665 _EVENT_LOG_ERR and _EVENT_LOG_NONE and will instruct Event::Lib to only
666 output messages of at least that severity. "_EVENT_LOG_NONE" will
667 suppress any messages. Not calling this function is equivalent to doing
668
669 event_log_level( _EVENT_LOG_ERR );
670
671 * $event->trace
672 This turns on tracing for $event. Tracing means that diagnostic
673 messages are written to STDERR whenever something happens to this
674 $event. This includes implicit action such as the destruction of an
675 event or explicit things like calling add() or remove() or other
676 methods on $event.
677
678 Returns $event so that you can easily plug it into your code:
679
680 event_new(...)->trace->add;
681
682 Once an event is traced, there is as of now no way to untrace it again.
683
684 * Event::Lib::Debug::get_pending_events()
685 This function is only available when you built Event::Lib with
686 "DEFINE=-DEVENT_LIB_DEBUG" (as an argument to perl Makefile.PL).
687 Additionally, you have to run your program with the environment
688 variable "EVENT_LIB_DEBUG_PENDING" set in order to get any output from
689 this function. The environment has to be set before "use Event::Lib;":
690
691 BEGIN {
692 $ENV{ EVENT_LIB_DEBUG_PENDING } = 1;
693 }
694
695 use Event::Lib;
696
697 or by setting it in your shell. For the bash, this looks like:
698
699 $ EVENT_LIB_DEBUG_PENDING=1 perl event_script.pl
700
701 This function will return a list of all currently still pending events.
702 Each element of this list is a reference to an array, where the first
703 element is the event object, the second the type of event
704 ("EV_TIMEOUT", "EV_SIGNAL", "EV_READ" etc.) and the remaining elements
705 the additional arguments this event was constructed with.
706
707 * Event::Lib::Debug::dump_pending_events()
708 Similar to the above, only that it will dump all currently pending
709 events to STDERR with some additional information that might be of
710 interest.
711
712 Again, this is only available when the module was build with
713 "-DEVENT_LIB_DEBUG" and with the environment variable
714 "EVENT_LIB_DEBUG_PENDING" set.
715
717 Event::Lib can be told which kernel notification method not to use.
718 This happens via the use of environment variables (there is no other
719 way due to libevent). They have to be set in a BEGIN-block before you
720 use() Event::Lib:
721
722 BEGIN {
723 $ENV{ $_ } = 1 for qw/EVENT_NOPOLL EVENT_NOEPOLL/;
724 }
725
726 use Event::Lib;
727
728 This will disable "poll" and "epoll" so it will use one of the
729 remaining methods, which could be either "select", "devpoll" or
730 "kqueue".
731
732 The variables that you may set are the following:
733
734 · EVENT_NOPOLL
735
736 · EVENT_NOSELECT
737
738 · EVENT_NOEPOLL
739
740 · EVENT_NODEVPOLL
741
742 · EVENT_NOKQUEUE
743
744 If you set all of the above variables, it is a fatal error and you'll
745 receive the message "event_init: no event mechanism available". There
746 is one other variable available:
747
748 · EVENT_LOG_LEVEL
749
750 This is the environment-variable version of set_log_level()
751 intended to conveniently run your script more verbosely for
752 debugging purpose. The lower this value is, the more informational
753 output libevent produces on STDERR. "EVENT_LOG_LEVEL=0" means
754 maximum debugging output whereas "EVENT_LOG_LEVEL=4" means no
755 output at all:
756
757 $ EVENT_LOG_LEVEL=0 perl your_script.pl
758
760 Here's a reasonably complete example how to use this library to create
761 a simple TCP server serving many clients at once. It makes use of all
762 three kinds of events:
763
764 use POSIX qw/SIGHUP/;
765 use IO::Socket::INET;
766 use Event::Lib;
767
768 $| = 1;
769
770 # Invoked when a new client connects to us
771 sub handle_incoming {
772 my $e = shift;
773 my $h = $e->fh;
774
775 my $client = $h->accept or die "Should not happen";
776 $client->blocking(0);
777
778 # set up a new event that watches the client socket
779 my $event = event_new($client, EV_READ|EV_PERSIST, \&handle_client);
780 $event->add;
781 }
782
783 # Invoked when the client's socket becomes readable
784 sub handle_client {
785 my $e = shift;
786 my $h = $e->fh;
787 printf "Handling %s:%s\n", $h->peerhost, $h->peerport;
788 while (<$h>) {
789 print "\t$_";
790 if (/^quit$/) {
791 # this client says goodbye
792 close $h;
793 $e->remove;
794 last;
795 }
796 }
797 }
798
799 # This just prints the number of
800 # seconds elapsed
801 my $secs;
802 sub show_time {
803 my $e = shift;
804 print "\r", $secs++;
805 $e->add;
806 }
807
808 # Do something when receiving SIGHUP
809 sub sighup {
810 my $e = shift;
811 # a common thing to do would be
812 # re-reading a config-file or so
813 ...
814 }
815
816 # Create a listening socket
817 my $server = IO::Socket::INET->new(
818 LocalAddr => 'localhost',
819 LocalPort => 9000,
820 Proto => 'tcp',
821 ReuseAddr => SO_REUSEADDR,
822 Listen => 1,
823 Blocking => 0,
824 ) or die $@;
825
826 my $main = event_new($server, EV_READ|EV_PERSIST, \&handle_incoming);
827 my $timer = timer_new(\&show_time);
828 my $hup = signal_new(SIGHUP, \&sighup);
829
830 $_->add for $main, $timer, $hup;
831
832 event_mainloop;
833
834 __END__
835
836 You can test the above server with this little program of which you can
837 start a few several simultaneous instances:
838
839 use IO::Socket::INET;
840
841 my $server = IO::Socket::INET->new(
842 Proto => 'tcp',
843 PeerAddr => 'localhost',
844 PeerPort => 9000,
845 ) or die $@;
846
847 print $server "HI!\n";
848 sleep 10;
849 print $server "quit\n";
850
851 __END__
852
854 There are already a handful of similar modules on the CPAN. The two
855 most prominent ones are Event and the venerable POE framework.
856
857 Event
858 In its functionality it's quite close to Event::Lib with some
859 additional features not present in this module (you can watch
860 variables, for example). Interface-wise, it's quite a bit heavier
861 while Event::Lib gets away with just a handful of functions and
862 methods. On the other hand, it has been around for years and so you may
863 expect Event to be rock-stable.
864
865 The one main advantage of Event::Lib appears to be in its innards. The
866 underlying libevent is capable of employing not just the "poll" and
867 "select" notification mechanisms but also other and possibly better
868 performing ones such as "kqueue", "devpoll" and "epoll" where
869 available.
870
871 POE
872 POE is definitely more than the above. It's really a threading
873 environment in disguise. Purely event-based techniques have
874 limitations, most notably that an event-handler blocks all other
875 pending events until it is done with its work. It's therefore not
876 possible to write a parallel link-checker only with Event or
877 Event::Lib. You still need threads or fork(2) for that.
878
879 That's where POE enters the scene. It is truely capable of running jobs
880 in parallel. Such jobs are usually encapsulated in "POE::Component"
881 objects of which already quite a few premade ones exist on the CPAN.
882
883 This power comes at a price. POE has a somewhat steep learning-curve
884 and forces you to think in POE concepts. For medium- and large-sized
885 applications, this doesn't have to be a bad thing. Once grokked, it's
886 easy to add more components to your project, so it's almost infinitely
887 extensible.
888
889 Stem
890 Stem is a very close rival to POE and they are nose-to-nose when it
891 comes to features. However, Stem's design is a lot easier to understand
892 and to adapt to your need, mostly because it doesn't come up with its
893 own methodology and terminology. It is very well thought out without
894 being over-designed.
895
896 It's easy and straight-forward to do simple event-looping (it currently
897 comes with its own well-conceived event loop; additionally it can make
898 use of Event when available). So called Stem cells can be easily
899 plugged together to build big applications where these cells can run in
900 parallel, both in an asynchronous or synchronized fashion.
901
902 It's main drawback (as of now) is its lack of documentation. However,
903 It's been written in a clean way so its source can often serve as a
904 drop-in replacement for the lack of documentation.
905
906 Conclusion
907 Use the right tools for your job. Event::Lib and Event are good for
908 writing servers that serve many clients at once, or in general:
909 Anything that requires you to watch resources and do some work when
910 something interesting happens with those resources. Once the work
911 needed to be carried out per event gets too complex, you may still use
912 "fork".
913
914 Or you use Stem or POE. You get the watching and notifying capabilities
915 alright, but also the power to do things in parallel without creating
916 threads or child processes manually.
917
919 This modules exports by default the following functions:
920
921 event_init
922 event_log_level
923 event_priority_init
924 event_register_except_handler
925 event_fork
926
927 event_new
928 timer_new
929 signal_new
930
931 event_add
932
933 event_mainloop
934 event_one_loop
935 event_one_nbloop
936
937 plus the following constants:
938
939 EV_PERSIST
940 EV_READ
941 EV_SIGNAL
942 EV_TIMEOUT
943 EV_WRITE
944 _EVENT_LOG_DEBUG
945 _EVENT_LOG_MSG
946 _EVENT_LOG_WARN
947 _EVENT_LOG_ERR
948 _EVENT_LOG_NONE
949
951 This library is not thread-safe.
952
953 The module has turned out to be quite stable under stress-situations
954 handling many thousands simultaneous connections with a very decent
955 performance which it owes to the underlying libevent. However, event-
956 based applications can reach a stupendous complexity and it is not
957 possible to foresee every kind of conceivable scenario.
958
959 If you therefore find a bug (a crash, a memory leak, inconsistencies or
960 omissions in this documentation, or just about anything else), don't
961 hesitate to contact me. See "AUTHOR" further below for details.
962
964 Thread-safety is high on the list. Recent libevent has thread-support
965 which will make this fairly easy.
966
967 Not all of libevent's public interface is implemented. The buffered
968 events are still missing. They will be added once I grok what they are
969 for.
970
972 This module wouldn't be in its current state without the patient and
973 professional help of MailChannels Corporation
974 (http://www.mailchannels.com). Over the course of five months, Stas
975 Bekman, Ken Simpson and Mike Smith exchanged hundreds of emails with
976 me, pointing out the many glitches that were in the module and coming
977 up with test-cases that made it possible for me to fix all these
978 issues.
979
981 libevent's home can be found at
982 <http://www.monkey.org/~provos/libevent/>. It contains further
983 references to event-based techniques.
984
985 Also the manpage of event(3).
986
988 This is version 1.03.
989
991 Tassilo von Parseval, <tassilo.von.parseval@rwth-aachen.de>
992
994 Copyright (C) 2004-2007 by Tassilo von Parseval
995
996 This library is free software; you can redistribute it and/or modify it
997 under the same terms as Perl itself, either Perl version 5.8.4 or, at
998 your option, any later version of Perl 5 you may have available.
999
1000
1001
1002perl v5.28.0 2007-07-29 Event::Lib(3)