如何在 Perl 中为长时间运行的 Sybase sp 设置超时
问题描述:
我正在调用一个存储过程,该过程从 Perl 中的 Sybase DB 中删除数据.但是 sp 需要几个小时才能完成.我只希望 sp 运行 1 小时,然后无论它是否完成,我都希望之后的代码运行.我该如何实施?
I'm calling a stored procedure which deletes data from Sybase DB in a Perl. But the sp takes hours to complete. I just want the sp to run for 1 hour, then no matter whether it completes or not I want the codes afterwards to be running. How can I implement this?
sub DelRef {
print "starting defRefData\n";
$db = new Sybapi($user, $password, $server, $margin_database);
#the following sql will take hours
$db->exec_sql("exec CPN_Margins..clean_up_refData_db '$XrefCode'");
}
&DelRef();
print "process is done\n";
$db->close();
答
我总是对使用 alarm
中断系统调用持谨慎态度,因为我发现很难预测信号何时会出现忽略了或更糟.
I'm always wary of using alarm
to interrupt a system call, as I find it hard to predict when the signal will be ignored or worse.
另一种方法是在后台进程中运行长时间运行的代码,并在主进程中监控其进度.
An alternative is to run your long-running code in a background process, and monitor its progress in the main process.
# DelRef() might take a while ...
my $start_time = time;
my $pid = fork();
if ($pid == 0) {
# child process
DelRef();
exit 0;
}
# parent process
while (1) {
use POSIX qw( WNOHANG );
my $waitpid = waitpid $pid, WNOHANG;
if ($pid == $waitpid) {
print STDERR "DelRef() finished successfully\n";
last;
}
if (time - $start_time > 3600) {
print STDERR "DelRef() didn't finish in an hour\n";
kill 'TERM',$pid; # optional
last;
}
print STDERR "DelRef() is still running ...\n";
sleep 60;
}
print STDERR "... the rest of the script ...\n";