Run a process in the background without being accepted by init, Perl

If I launch an external process through a Perl program, the perl program remains the parent of the process. Easy process management.

system('sleep 3000'); # perl is still the parent

      

However, if I try to start the process in the background so that the program doesn't wait for the process to finish ...

system('sleep 3000 &'); 

      

The process sleep

will be accepted by the system process init

and is no longer associated with the program that executed it.

What is the correct way to manage the process in this situation. How can I emulate the execution of a process in the background but maintain the process's pedigree?

+1


source to share


2 answers


You can use threads

,

use threads;
my $t = async { system('sleep 3000'); };

# do something in parallel ..

# wait for thread to finish 
$t->join;

      



or fork

sub fasync(&) {
  my ($worker) = @_;

  my $pid = fork() // die "can't fork!"; 
  if (!$pid) { $worker->(); exit(0); }

  return sub {
    my ($flags) = @_;
    return waitpid($pid, $flags // 0);
  }
}

my $t = fasync { system('sleep 3000'); };

# do something in parallel ..

# wait for fork to finish 
$t->();

      

+2


source


fork / exec and wait ().

Fork creates a child process by creating a copy of the parent, the parent gets the process ID of the child and calls wait () on the child's process ID.



Meanwhile, the child process uses exec () to overlay itself (a copy of the parent) with the process you want to execute.

If you need multiple parallel background jobs, I recommend Parallel :: ForkManager .

0


source







All Articles