How can I terminate a system command with alarm in Perl?

user285686 picture user285686 · Apr 1, 2010 · Viewed 13.5k times · Source

I am running the below code snippet on Windows. The server starts listening continuously after reading from client. I want to terminate this command after a time period.

If I use alarm() function call within main.pl, then it terminates the whole Perl program (here main.pl), so I called this system command by placing it in a separate Perl file and calling this Perl file (alarm.pl) in the original Perl File using the system command.

But in this way I was unable to take the output of this system() call neither in the original Perl File nor in called one Perl File.

Could anybody please let me know the way to terminate a system() call or take the output in that way I used above?

main.pl

my @output = system("alarm.pl");
print"one iperf completed\n";

open FILE, ">display.txt" or die $!; 
print FILE @output_1; 
close FILE;

alarm.pl

alarm 30;
my @output_1 = readpipe("adb shell cd /data/app; ./iperf -u -s -p 5001");

open FILE, ">display.txt" or die $!; 
print FILE @output_1; 
close FILE;

In both ways display.txt is always empty.

Answer

brian d foy picture brian d foy · Apr 1, 2010

There are a few separate issues here.

First, to keep the alarm from killing your script, you need to handle the ALRM signal. See the alarm documentation. You shouldn't need two scripts for this.

Second, system doesn't capture output. You need one of the backtick variants or a pipe if you want to do that. There are answers for that on Stackoverflow already.

Third, if alarm.pl puts anything in display.txt, you discard it in main.pl when you re-open the file in write mode. You only need to create the file in one place. When you get rid of the extra script, you won't have this problem.

I recently had some problems with alarm and system, but switching to IPC::System::Simple fixed that.

Good luck, :)