Tuesday, 9 August 2011

Fork a child process from parent and execute a child

This can be done using Fork and Exec Combination as said by Larry Wall:


if ($pid=fork) { # assign result of fork to $pid,

# see if it is non-zero.

# Parent process here

# Child pid is in $pid

print "child pid : $pid\n";

sleep $delay;


if(kill 0 => $pid) {#kill 0 checks whether a process is alive or not

push @pids,$pid; #Collect child pids who exceeded time limit or alive after delay


foreach my $pid (@pids) {

kill 9,$pid;

Debug("killing child script process $pid");

Debug("child script process $pid exited with RC=32;$RCDesc{32}");


Debug("Ending gsma_wrapper");



} elsif (defined($pid)) {

# Child process here

# parent process pid is available with getppid

my $ppid = getppid();

print "parent pid : $ppid\n";

# exec will transfer control to the child process, and will

# finish (exit) when the scirpt is done.

my $cmd = "sh $action_script";

Debug("executing action_script $cmd");

exec("$cmd 1>./stdout 2>./stderr") or log_exit("Action script $action_script failed with RC=10;$RCDesc{10}");


} elsif ($! == EAGAIN) {

# EAGAIN is the supposedly recoverable fork error

sleep 5;

redo FORK;

} else {

#weird fork error

Debug("Can't fork action script $action_script: $!");



# wait for the action scrpt to complete and return status (like system does)


$status = $?;

No comments:

Post a Comment

Tweets by @sriramperumalla