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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.