Notify parent that a background process failed

P

pat

Hi,

I have a Perl script that basically takes a list of Unix commands and
executes them one by one, does something with the output and goes to
execute the next, some of these commands have to be executed in the
background, the script does not wait for them to finish, just starts it
and keeps going, the problem is that I do need to know if any of the
background processes fail and the return code. I tried using $SIG{CHLD}
but I get a signal for every one of the commands I run, I'm only
interested in the background ones. Is there a way to do a non-blocking
wait on a specific process id?

I use fork to start the process:

if (!defined($pid = fork))
{ # Fork failed
error_message("Couldn't create new process");
return 1;
}
elsif ($pid==0)
{
# Child process block
print "child proccess id is $pid \n";
exec("my_child_command", @args);
}
else
{
# Parent process continues here
print "Copa proccess id is $pid \n";
$status = 0;
# Make sure process started
unless (kill 0 => $pid)
{
print "Background process is not running \n";
return 1;
}
,,,,,,

Any help will be greatly appreciated
Patricia
 
P

Peter J. Holzer

I have a Perl script that basically takes a list of Unix commands and
executes them one by one, does something with the output and goes to
execute the next, some of these commands have to be executed in the
background, the script does not wait for them to finish, just starts it
and keeps going, the problem is that I do need to know if any of the
background processes fail and the return code. I tried using $SIG{CHLD}
but I get a signal for every one of the commands I run, I'm only
interested in the background ones. Is there a way to do a non-blocking
wait on a specific process id?

perldoc -f waitpid

But if you are starting several background processes, you probably don't
want to wait for a specific process. Instead you want to record the pids
of the background processes, and when a process terminates you check if
it is one of those you are interested in, else you ignore it.

I use fork to start the process:

if (!defined($pid = fork))
{ # Fork failed [...]
}
elsif ($pid==0)
{ [...]
}
else
{
# Parent process continues here [...]
# Make sure process started
unless (kill 0 => $pid)
{
print "Background process is not running \n";
return 1;
}

There is a race condition here. The child process may already have
terminated when the parent gets here. Also, it is useless: You already
know that the child process was started since fork didn't return undef.

hp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top