perl运行后台工作和强制工作完成?

时间:2013-09-26 13:36:04

标签: perl ipc kill-process

我有一个Perl脚本启动后台作业来打印一些 将信息记录到文件中,然后执行某些操作 饰面。

我想在脚本完成时结束后台进程, 但据我所知,如果我使用如下所示的双叉,那么waitpid($pid,0) 将等待后台进程完成,而不是杀死它, 并且kill(9,$pid)不会摆脱后台进程。

示例脚本:

#!/usr/bin/perl
use strict;

# Do a first general top
my $ret = `top -b -n 1 > logfile`;

# Do a background $USER top every minute
my $cmd = "top -b -d 60 -n 300 -u $ENV{USER} >> logfile";
my $pid;
unless ($pid = fork) {
  unless (fork) {       #second_fork
    exec "$cmd";
    die "exec failed!";
  }                     #second_fork
  exit 0;
}

# Script does something else for 1-2 hours
# [...]
# We are finished now, let's finish the logging

# waitpid($pid,0) would wait until top command is finished
force_background_job_to_finish($pid) if (background_job_still_running($pid));

# Add final top to the end
$ret = `top -b -n 1 >> logfile`;

1;

任何想法如何force_background_job_to_finish

2 个答案:

答案 0 :(得分:2)

通常使用双叉,因此您不必担心收获子进程。由于你想要控制子进程,你可以只做一个fork,它将为你提供进程id,然后你可以使用kill来杀死你的子进程。

答案 1 :(得分:2)

这对我有用:

$SIG{CHLD}="IGNORE";
my $cmd = "top -b -d 60 -n 300 -u $ENV{USER} >> logfile";
if (my $logger_pid=fork) {
    # parent
    do_something_for_1to2_hours();
    kill 15, $logger_pid;
} else {
    # child (logger)
    exec($cmd);
}