Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Execute shell command, grab it's return, terminate on timeout

by wind (Priest)
on Mar 21, 2014 at 00:52 UTC ( #1079148=note: print w/replies, xml ) Need Help??


in reply to Execute shell command, grab it's return, terminate on timeout

This is a side note about code style suggestions

1) It really would be wise to use named parameters for all your methods. Your code would become self-documenting and you wouldn't have to preface your code with a description of what your parameters were when posting on perlmonks.

2) You also have a comment next to @cmd, describing it as a return value. Why not just name it @return_val? Then no need for a comment.

3) Finally, if you look at the documentation for alarm, you'll see a suggestion on how to propagate errors that don't revolve around the alarm. If your command fails on things other than the Timeout, you're probably going to want to know that.

sub exec_safe { my ($command, $timeout, $nice_val) = @_; my @return_val; eval { local $SIG{ALRM} = sub { die "Timeout\n" }; alarm $timeout; @return_val= `nice -n $nice_val $command`; alarm 0; }; if($@) { # If command fails, return non-zero and msg die unless $@ eq "Timeout\n"; # propagate unexpected errors return ("Command timeout",1); } else { chomp @return_val; push(@return_val, $? >> 8); return @return_val; } }

Good luck getting assistance with your requested problem,

- Miller

Replies are listed 'Best First'.
Re^2: Execute shell command, grab it's return, terminate on timeout
by Haioken (Novice) on Mar 21, 2014 at 03:08 UTC
    Hi Miller, Thanks for the suggestions.

    1) It's probably left over from days of developing in C for Atmel MicroControllers. Limited memory partly means declaring as few as possible variables. Probably not so much an issue with my servers having >16Gb RAM.

    2) No excuse for that one. Uhhh ... made sense at the time? :o)

    3) I've made this change in my live code, though I'm not sure what circumstances would call it, as the other fails get reported via:

    push(@return_val, $? >> 8);

    The STDOUT data is already in @return_val (or @cmd), and the command above will give me the spawned process' exit code.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1079148]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2022-12-03 23:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?