Reputation: 3245
I am trying to write a perl script that executes external program and stop it.
The external program will not stop by itself because I am supposed to hit 'enter' on command shell it is running on.
Is there any way to stop the external program in perl script?
Upvotes: 2
Views: 757
Reputation: 1771
Is there any way to stop the external program in perl script?
In a word, yes. But the implementation depends on the platform on which you're running your application.
On all the platforms that perl supports, you could use system()
to call an external program. But then your original program will wait and do nothing until the external program exits, so system()
doesn't fit your situation.
Since you didn't mention your platform (OS), two main platforms should be talked here:
Unix-like OS: First of all you could fork
a child process, and in child process, use exec
to call the external program. Then in parent process, you could wait the child process, and send it TERM
signals (or other signals which will terminate the process by default) when you would like to stop the external program.
if (($pid = fork) == 0) {
exec("$external_program $arg");
} else {
# do something...
kill "TERM", $pid;
}
Win32 OS: I would like to mention that on Win32 platform, the child process fork
ed is actually a pseudo-process, and Win32 doesn't support the signal methodology like Unix. You could follow the solution in 1
for Win32, but as far as I tried, child process often misses the signals, for example, when child process is sleeping or waiting for a socket connection. This could be very unstable.
Instead, Win32::Process is a better solution. It use Win32 API to create and manipulate processes.
use Win32::Process;
use Win32;
Win32::Process::Create($ProcessObj, $external_program, $arg,
0, NORMAL_PRIORITY_CLASS, ".") or die;
# do something ...
$ProcessObj->Kill($exitcode);
Basically that's the principle. If you want a cross-platform solution, there's a module Proc::Background on CPAN, which supports both platforms.
use Proc::Background;
my $proc = Proc::Background->new($command, $arg);
# do something ...
$proc->die;
Upvotes: 1
Reputation: 963
I think you could use a fork in Perl to get the pid (process id) of the child process. See the last comment here.
Once you have pid you can use the Unix kill
(see this site) command from your Perl script using any of the methods described here.
This question also indicates that you could write the pid from inside whatever program you started to a separate file. You could then read in the pid in that file from your calling script.
Upvotes: 0