perl运行后台作业并强制完成作业? [英] perl run background job and force job to finish?

查看:69
本文介绍了perl运行后台作业并强制完成作业?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Perl脚本,可以启动后台作业以打印一些内容 将信息记录到文件中,执行某些操作,然后 完成.

I've got a Perl script that starts a background job to print some logging information into a file, executes something, and then finishes.

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

I would like to end the background process when the script is done, but as far as I know, if I use a double fork as below, then waitpid($pid,0) will wait for the background process to finish, instead of killing it, and kill(9,$pid) won't get rid of the background process.

示例脚本:

#!/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?

推荐答案

这对我有用:

$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);
}

这篇关于perl运行后台作业并强制完成作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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