1Event::Lib(3)         User Contributed Perl Documentation        Event::Lib(3)
2
3
4

NAME

6       Event::Lib - Perl extentions for event-based programming
7

SYNOPSIS

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

DESCRIPTION

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

INITIALIZATION

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

EVENTS

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

Watching filehandles

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

Timer-based events

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

Signal-based events

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

COMMON METHODS

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

ENTERING THE EVENT-LOOP

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

EVENT LIFECYCLE

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

EXCEPTION HANDLING

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 event.
632

PRIORITIES

634       Events can be assigned a priority. The lower its assigned priority is,
635       the earlier this event is processed. Using prioritized events in your
636       programs requires two steps. The first one is to set the number of
637       available priorities.  Setting those should happen once in your script
638       and before calling event_mainloop():
639
640   * event_priority_init( $priorities )
641       Sets the number of different events to $priorities.
642
643       Assigning a priority to each event then happens thusly:
644
645   * $event->set_priority( $priority )
646       Gives $event (which can be any of the three type of events) the
647       priority $priority. Remember that a lower priority means the event is
648       processed earlier!
649
650       Note: If your installed version of libevent does not yet contain
651       priorities which happens for pre-1.0 versions, the above will become
652       no-ops. Other than that, your scripts will remain functional.
653

FUNCTIONS FOR DEBUGGING, TRACING ET AL.

655       There are some functions that will aid you in finding problems in your
656       program or even to assure you that your program is ok but there might
657       be a bug in Event::Lib.
658
659   * event_log_level( $loglevel )
660       You can specify what kind of messages Event::Lib should dump to stderr
661       by using thid function.
662
663       $loglevel is one of _EVENT_LOG_DEBUG, _EVENT_LOG_MSG, _EVENT_LOG_WARN,
664       _EVENT_LOG_ERR and _EVENT_LOG_NONE and will instruct Event::Lib to only
665       output messages of at least that severity. "_EVENT_LOG_NONE" will
666       suppress any messages. Not calling this function is equivalent to doing
667
668           event_log_level( _EVENT_LOG_ERR );
669
670   * $event->trace
671       This turns on tracing for $event. Tracing means that diagnostic
672       messages are written to STDERR whenever something happens to this
673       $event. This includes implicit action such as the destruction of an
674       event or explicit things like calling add() or remove() or other
675       methods on $event.
676
677       Returns $event so that you can easily plug it into your code:
678
679           event_new(...)->trace->add;
680
681       Once an event is traced, there is as of now no way to untrace it again.
682
683   * Event::Lib::Debug::get_pending_events()
684       This function is only available when you built Event::Lib with
685       "DEFINE=-DEVENT_LIB_DEBUG" (as an argument to perl Makefile.PL).
686       Additionally, you have to run your program with the environment
687       variable "EVENT_LIB_DEBUG_PENDING" set in order to get any output from
688       this function. The environment has to be set before "use Event::Lib;":
689
690           BEGIN {
691               $ENV{ EVENT_LIB_DEBUG_PENDING } = 1;
692           }
693
694           use Event::Lib;
695
696       or by setting it in your shell. For the bash, this looks like:
697
698           $ EVENT_LIB_DEBUG_PENDING=1 perl event_script.pl
699
700       This function will return a list of all currently still pending events.
701       Each element of this list is a reference to an array, where the first
702       element is the event object, the second the type of event
703       ("EV_TIMEOUT", "EV_SIGNAL", "EV_READ" etc.) and the remaining elements
704       the additional arguments this event was constructed with.
705
706   * Event::Lib::Debug::dump_pending_events()
707       Similar to the above, only that it will dump all currently pending
708       events to STDERR with some additional information that might be of
709       interest.
710
711       Again, this is only available when the module was build with
712       "-DEVENT_LIB_DEBUG" and with the environment variable
713       "EVENT_LIB_DEBUG_PENDING" set.
714

CONFIGURATION

716       Event::Lib can be told which kernel notification method not to use.
717       This happens via the use of environment variables (there is no other
718       way due to libevent). They have to be set in a BEGIN-block before you
719       use() Event::Lib:
720
721           BEGIN {
722               $ENV{ $_ } = 1 for qw/EVENT_NOPOLL EVENT_NOEPOLL/;
723           }
724
725           use Event::Lib;
726
727       This will disable "poll" and "epoll" so it will use one of the
728       remaining methods, which could be either "select", "devpoll" or
729       "kqueue".
730
731       The variables that you may set are the following:
732
733       •   EVENT_NOPOLL
734
735       •   EVENT_NOSELECT
736
737       •   EVENT_NOEPOLL
738
739       •   EVENT_NODEVPOLL
740
741       •   EVENT_NOKQUEUE
742
743       If you set all of the above variables, it is a fatal error and you'll
744       receive the message "event_init: no event mechanism available". There
745       is one other variable available:
746
747       •   EVENT_LOG_LEVEL
748
749           This is the environment-variable version of set_log_level()
750           intended to conveniently run your script more verbosely for
751           debugging purpose. The lower this value is, the more informational
752           output libevent produces on STDERR. "EVENT_LOG_LEVEL=0" means
753           maximum debugging output whereas "EVENT_LOG_LEVEL=4" means no
754           output at all:
755
756               $ EVENT_LOG_LEVEL=0 perl your_script.pl
757

EXAMPLE: A SIMPLE TCP SERVER

759       Here's a reasonably complete example how to use this library to create
760       a simple TCP server serving many clients at once. It makes use of all
761       three kinds of events:
762
763           use POSIX qw/SIGHUP/;
764           use IO::Socket::INET;
765           use Event::Lib;
766
767           $| = 1;
768
769           # Invoked when a new client connects to us
770           sub handle_incoming {
771               my $e = shift;
772               my $h = $e->fh;
773
774               my $client = $h->accept or die "Should not happen";
775               $client->blocking(0);
776
777               # set up a new event that watches the client socket
778               my $event = event_new($client, EV_READ|EV_PERSIST, \&handle_client);
779               $event->add;
780           }
781
782           # Invoked when the client's socket becomes readable
783           sub handle_client {
784               my $e = shift;
785               my $h = $e->fh;
786               printf "Handling %s:%s\n", $h->peerhost, $h->peerport;
787               while (<$h>) {
788                   print "\t$_";
789                   if (/^quit$/) {
790                       # this client says goodbye
791                       close $h;
792                       $e->remove;
793                       last;
794                   }
795               }
796           }
797
798           # This just prints the number of
799           # seconds elapsed
800           my $secs;
801           sub show_time {
802               my $e = shift;
803               print "\r", $secs++;
804               $e->add;
805           }
806
807           # Do something when receiving SIGHUP
808           sub sighup {
809               my $e = shift;
810               # a common thing to do would be
811               # re-reading a config-file or so
812               ...
813           }
814
815           # Create a listening socket
816           my $server = IO::Socket::INET->new(
817               LocalAddr   => 'localhost',
818               LocalPort   => 9000,
819               Proto       => 'tcp',
820               ReuseAddr   => SO_REUSEADDR,
821               Listen      => 1,
822               Blocking    => 0,
823           ) or die $@;
824
825           my $main  = event_new($server, EV_READ|EV_PERSIST, \&handle_incoming);
826           my $timer = timer_new(\&show_time);
827           my $hup   = signal_new(SIGHUP, \&sighup);
828
829           $_->add for $main, $timer, $hup;
830
831           event_mainloop;
832
833           __END__
834
835       You can test the above server with this little program of which you can
836       start a few several simultaneous instances:
837
838           use IO::Socket::INET;
839
840           my $server = IO::Socket::INET->new(
841               Proto       => 'tcp',
842               PeerAddr    => 'localhost',
843               PeerPort    => 9000,
844           ) or die $@;
845
846           print $server "HI!\n";
847           sleep 10;
848           print $server "quit\n";
849
850           __END__
851

OTHER EVENT MODULES

853       There are already a handful of similar modules on the CPAN. The two
854       most prominent ones are Event and the venerable POE framework.
855
856   Event
857       In its functionality it's quite close to Event::Lib with some
858       additional features not present in this module (you can watch
859       variables, for example).  Interface-wise, it's quite a bit heavier
860       while Event::Lib gets away with just a handful of functions and
861       methods. On the other hand, it has been around for years and so you may
862       expect Event to be rock-stable.
863
864       The one main advantage of Event::Lib appears to be in its innards. The
865       underlying libevent is capable of employing not just the "poll" and
866       "select" notification mechanisms but also other and possibly better
867       performing ones such as "kqueue", "devpoll" and "epoll" where
868       available.
869
870   POE
871       POE is definitely more than the above. It's really a threading
872       environment in disguise. Purely event-based techniques have
873       limitations, most notably that an event-handler blocks all other
874       pending events until it is done with its work.  It's therefore not
875       possible to write a parallel link-checker only with Event or
876       Event::Lib. You still need threads or fork(2) for that.
877
878       That's where POE enters the scene. It is truely capable of running jobs
879       in parallel. Such jobs are usually encapsulated in "POE::Component"
880       objects of which already quite a few premade ones exist on the CPAN.
881
882       This power comes at a price. POE has a somewhat steep learning-curve
883       and forces you to think in POE concepts. For medium- and large-sized
884       applications, this doesn't have to be a bad thing. Once grokked, it's
885       easy to add more components to your project, so it's almost infinitely
886       extensible.
887
888   Stem
889       Stem is a very close rival to POE and they are nose-to-nose when it
890       comes to features. However, Stem's design is a lot easier to understand
891       and to adapt to your need, mostly because it doesn't come up with its
892       own methodology and terminology. It is very well thought out without
893       being over-designed.
894
895       It's easy and straight-forward to do simple event-looping (it currently
896       comes with its own well-conceived event loop; additionally it can make
897       use of Event when available). So called Stem cells can be easily
898       plugged together to build big applications where these cells can run in
899       parallel, both in an asynchronous or synchronized fashion.
900
901       It's main drawback (as of now) is its lack of documentation. However,
902       It's been written in a clean way so its source can often serve as a
903       drop-in replacement for the lack of documentation.
904
905   Conclusion
906       Use the right tools for your job. Event::Lib and Event are good for
907       writing servers that serve many clients at once, or in general:
908       Anything that requires you to watch resources and do some work when
909       something interesting happens with those resources. Once the work
910       needed to be carried out per event gets too complex, you may still use
911       "fork".
912
913       Or you use Stem or POE. You get the watching and notifying capabilities
914       alright, but also the power to do things in parallel without creating
915       threads or child processes manually.
916

EXPORT

918       This modules exports by default the following functions:
919
920           event_init
921           event_log_level
922           event_priority_init
923           event_register_except_handler
924           event_fork
925
926           event_new
927           timer_new
928           signal_new
929
930           event_add
931
932           event_mainloop
933           event_one_loop
934           event_one_nbloop
935
936       plus the following constants:
937
938           EV_PERSIST
939           EV_READ
940           EV_SIGNAL
941           EV_TIMEOUT
942           EV_WRITE
943           _EVENT_LOG_DEBUG
944           _EVENT_LOG_MSG
945           _EVENT_LOG_WARN
946           _EVENT_LOG_ERR
947           _EVENT_LOG_NONE
948

BUGS

950       This library is not thread-safe.
951
952       The module has turned out to be quite stable under stress-situations
953       handling many thousands simultaneous connections with a very decent
954       performance which it owes to the underlying libevent. However, event-
955       based applications can reach a stupendous complexity and it is not
956       possible to foresee every kind of conceivable scenario.
957
958       If you therefore find a bug (a crash, a memory leak, inconsistencies or
959       omissions in this documentation, or just about anything else), don't
960       hesitate to contact me. See "AUTHOR" further below for details.
961

TO-DO

963       Thread-safety is high on the list. Recent libevent has thread-support
964       which will make this fairly easy.
965
966       Not all of libevent's public interface is implemented. The buffered
967       events are still missing. They will be added once I grok what they are
968       for.
969

THANKS

971       This module wouldn't be in its current state without the patient and
972       professional help of MailChannels Corporation
973       (http://www.mailchannels.com).  Over the course of five months, Stas
974       Bekman, Ken Simpson and Mike Smith exchanged hundreds of emails with
975       me, pointing out the many glitches that were in the module and coming
976       up with test-cases that made it possible for me to fix all these
977       issues.
978

SEE ALSO

980       libevent's home can be found at
981       <http://www.monkey.org/~provos/libevent/>. It contains further
982       references to event-based techniques.
983
984       Also the manpage of event(3).
985

VERSION

987       This is version 1.03.
988

AUTHOR

990       Tassilo von Parseval, <tassilo.von.parseval@rwth-aachen.de>
991
993       Copyright (C) 2004-2007 by Tassilo von Parseval
994
995       This library is free software; you can redistribute it and/or modify it
996       under the same terms as Perl itself, either Perl version 5.8.4 or, at
997       your option, any later version of Perl 5 you may have available.
998
999
1000
1001perl v5.38.0                      2023-07-20                     Event::Lib(3)
Impressum