1 |
#!/usr/bin/perl |
2 |
|
3 |
use warnings; |
4 |
use strict; |
5 |
|
6 |
use POE qw( Wheel::Run Filter::Line ); |
7 |
|
8 |
# Start the session. Spawn a simple program, and describe the events |
9 |
# it will generate as it does things. |
10 |
|
11 |
sub _start { |
12 |
my ( $kernel, $heap ) = @_[ KERNEL, HEAP ]; |
13 |
|
14 |
$heap->{child} = POE::Wheel::Run->new |
15 |
#( Program => [ "/bin/ls", "-1", "/" ], # Program to run. |
16 |
( Program => [ "dir", "-1", "/" ], # Program to run. |
17 |
#( Program => [ "bin/ls.exe", "-1", "/" ], # Program to run. |
18 |
Filter => POE::Filter::Line->new(), # Child speaks in lines. |
19 |
StdoutEvent => "got_child_stdout", # Child wrote to STDOUT. |
20 |
StderrEvent => "got_child_stderr", # Child wrote to STDERR. |
21 |
#CloseEvent => "got_child_close", # Child stopped writing. |
22 |
); |
23 |
} |
24 |
|
25 |
# Deal with information the child wrote to its STDOUT. |
26 |
|
27 |
sub got_child_stdout { |
28 |
my $stdout = $_[ARG0]; |
29 |
print "STDOUT: $stdout\n"; |
30 |
} |
31 |
|
32 |
# Deal with information the child wrote to its STDERR. These are |
33 |
# warnings and possibly error messages. |
34 |
|
35 |
sub got_child_stderr { |
36 |
my $stderr = $_[ARG0]; |
37 |
$stderr =~ tr[ -~][]cd; |
38 |
print "STDERR: $stderr\n"; |
39 |
} |
40 |
|
41 |
# The child has closed its output filehandles. It will not be sending |
42 |
# us any more information, so destroy it. |
43 |
|
44 |
sub got_child_close { |
45 |
my $heap = $_[HEAP]; |
46 |
print "child closed.\n"; |
47 |
delete $heap->{child}; |
48 |
} |
49 |
|
50 |
# A list of functions that will handle the events they're named after. |
51 |
|
52 |
my @handlers = |
53 |
qw( _start got_child_stdout got_child_stderr got_child_close |
54 |
); |
55 |
|
56 |
# Start a session where each event is handled by a function with the |
57 |
# same name. Run POE's Kernel (and thus all its sessions) until done. |
58 |
|
59 |
POE::Session->create( package_states => [ main => \@handlers ] ); |
60 |
$poe_kernel->run(); |
61 |
|