Hello Monks,
I'm seeking for you wisdom and hope that someone can help me a bit.
I wrote a little daemon that executes programs with IPC::Open3 and intercepts the output from stdout and stderr. IO::Select is used to check if a handle is ready and alarm() for timeouts within eval{}.
The daemon is running very nice on linux, but unfortunately not on windows.
Now I was searching for another solution and thought about to use threads.
In the following example a thread is created to execute a program. The parent waits until $timeout and then detach the thread and kills the process that is maybe still running.
#!perl.exe
use strict;
use warnings;
use threads;
use threads::shared;
use Data::Dumper;
use IPC::Open3;
use Symbol;
my %data : shared;
my $timeout = 3;
my $command = "perl test.pl";
my $tid = threads->create(sub { execute($command) });
while (--$timeout) {
if ($tid->is_joinable) {
$tid->join;
last;
}
sleep 1;
}
if ($timeout == 0) {
if ($data{pid}) {
kill -9, $data{pid};
}
$tid->detach;
$data{timedout} = 1;
}
print Dumper(\%data);
sub execute {
my $in = Symbol::gensym();
my $out = Symbol::gensym();
my $err = Symbol::gensym();
my $pid = open3($in, $out, $err, @_);
close $in;
$data{pid} = $pid;
# sorry for that dirty handling of $out and $err :-)
# it was just a hack for tests
$data{stdout} = do { local $/; <$out> };
$data{stderr} = do { local $/; <$err> };
close $out;
close $err;
threads->exit;
}
Now my question to you is: could it be simplier? I don't know if my code example is too much dirty, because I haven't the finest idea of windows.
I would be very pleased for your wisdom.
Cheers
Jonny
Edit: a short code fix
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|