gpt4 book ai didi

linux - "if"条件未按预期工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:16 26 4
gpt4 key购买 nike

我发现我的 Perl 脚本有两个问题:

  • 我的 if 条件有 ==.!= 等失败

  • ps -p $pid -o etime= 抛出错误 sh: line 1: -o: command not found

    <

我正在尝试检查一个进程是否已经在运行,如果是的话

  • 如果它已经运行超过 40 分钟,则终止该进程

  • 如果它已经运行了 30-40 分钟,则发出通知

  • 如果运行不到30分钟则退出

一个简单的 if 测试也失败了。我在最后附上了示例代码。

有人可以告诉我这些问题的原因吗?

if ( `ps -ef | grep example | grep -v grep` ) {

print "Process is already running\n";

my $pid = `ps -ef | grep example | grep -v grep | awk '{print \$2}'`;

if ( `ps -p $pid -o etime= | sed -e "s/:/\\n/g" | wc -l | grep 3` ) {

print "1. Running for more than 40 mins\n";
`ps -ef | grep example | grep -v grep | awk '{print \$2}' | xargs kill -9`;
}
elsif ( `ps -p $pid -o etime= | sed -e "s/:/\\n/g" | wc -l|grep "2"` ) {

my $pmin = `ps -p $pid -o etime= | awk -F: '{print \$1}'`;

if ( $pmin < 30 ) {

print "Process running for 15 mins. Exiting";
exit;
}
elsif ( $pid >= 40 ) {

print "2.Running for more than 40 mins\n";
`ps -ef | grep example | grep -v grep | awk '{print \$2}' | xargs kill -9`;
}
else {

print "Process running for 30 mins. Notify";
}
}
}

my $psc = `ps -ef | grep example | grep -v grep >/dev/null 2>&1 && echo "Yes" || echo "No"`;
print "PSC - $psc";

if ( $psc eq "Yes" ) {
print "running";
}
else {
print "not running";
}

./test.pl

PSC - Yes 
not running

最佳答案

我认为这可能是您问题的根源:

elsif ($pid >= 40) {

因为那是进程 ID。不是 $pmin。所以你基本上是杀死进程 ID > 40,这几乎是任何进程,除了偶尔随机获得低 pid 之外。

但从根本上讲 - 炮击到 psgrep 是痛苦的。将 : 替换为 \n 然后计算行数是一件令人讨厌的事情 - 然后使用 grep 来匹配字符串也是很脏。

为什么不改用 Proc::ProcessTable 之类的东西来重写呢?

这是一个示例,说明您如何读取进程表、查找特定进程 ID(或一组)然后查询时间:

#!/usr/bin/env perl

use strict;
use warnings;

use Proc::ProcessTable;
use Data::Dumper;

my $ps = Proc::ProcessTable->new;

my @target_processes = grep { $_->pid eq $$ } @{ $ps->table };

print Dumper \@target_processes;

sleep 10;

while (1) {

foreach my $process ( grep { $_->cmndline =~ m/perl/ } @{ $ps->table } ) {
sleep 5;
print $process ->cmndline, " has been running for ",
$process->time / 10000, "s\n";
print Dumper \$process;
}

}

注意 - time 是高分辨率时间

关于linux - "if"条件未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49750815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com