在后台运行进程而不被init,Perl所采用 [英] run process in background without being adopted by init, Perl

查看:77
本文介绍了在后台运行进程而不被init,Perl所采用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我通过perl程序运行外部进程,则perl程序将仍然是该进程的父级.简化流程管理.

If I run an external process via a perl program,the perl program will remain the parent of the process. Making process management easy.

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

但是,如果我尝试在后台运行该进程,则程序不必等待进程退出...

However if I try to run the process in the background so that the program does not have to wait for the process to exit...

system('sleep 3000 &'); 

sleep进程将由系统init进程采用,并且不再与执行它的程序相关联.

The sleep process will be adopted by the systems init process and is no longer associated with the program that executed it.

在这种情况下处理流程管理的正确方法是什么?如何模拟在后台运行流程但保持流程祖先?

What is the proper way to handle process management in this situation. How can I emulate running the process in the background but maintain process ancestry?

推荐答案

您可以使用 threads

You can use threads,

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

# do something in parallel ..

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

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->();

这篇关于在后台运行进程而不被init,Perl所采用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆