I want to create a program in perl which is able to start and kill child processes.
Specifics: When given a command, the parent will spawn a new child process and pass it arguments as needed via command line. Once the child process has started the parent will move on and wait for another command. The commands are either to start a process or stop a specific process.
The parent should never wait on the child processes. All children will be able to exit gracefully and cleanup as needed. However, the parent will need to track and kill any individual child process as desired.
I am currently building this parent script but would like to know if I am using the correct perl functions and what's the best practice for doing this.
I will use one of the following Perl functions and a combination of waitpid($pid, WNOHANG) and kill('TERM', $pid). Is this the right approach? Is there a ready-built solution for this? What's the best practice here?
system function exec function backticks (``) operator open function
Here is my working code.
sub spawnNewProcess
{
my $message = shift;
# Create a new process
my $pid = fork;
if (!$pid)
{
# We're in the child process here. We'll spawn an instance and exit once done
&startInstance( $message );
die "Instance process for $message->{'instance'} has completed.";
}
elsif($pid)
{
# We're in the parent here. Let's save the child pid.
$INSTANCES->{ $message->{'instance'} } = $pid;
}
}
sub stopInstance
{
my $message = shift;
# Check to see if we started the specified instnace
my $pid = $INSTANCES->{$message->{'instance'}};
if( $pid )
{
# If we did, then check to see if it's still running
while( !waitpid($pid, WNOHANG) )
{
# If it is, then kill it gently
kill('TERM', $pid);
# Wait a couple seconds
sleep(3);
# Kill it forceably if gently didn't work
kill('KILL', $pid) if( !waitpid($pid, WNOHANG) );
}
}
}
daemontools
orsupervisord
? – jordanm