代码之家  ›  专栏  ›  技术社区  ›  Red Cricket

有没有更好的方法检测我的Perl脚本是从“firstboot”调用的?

  •  2
  • Red Cricket  · 技术社区  · 10 年前

    我有一个Perl脚本,如果它被firstboot脚本调用或被firstboot生成的进程调用,它需要以特定的方式运行。我有这个常规 handleFirstBoot 它看起来还可以,但可能有更好的方法来编写这个例程。所以请看一下。。。

    sub handleFirstBoot {
        my $child_id = shift || $$;
        my $parent_id;
        foreach (`ps -ef`) {
            my ($uid,$pid,$ppid) = split;
            next unless ($pid eq $child_id);
            $parent_id = $ppid;
            last;
        }    
        if ( $parent_id == 0 ) {
            debug "firstboot is NOT an ancestor.\n";
            return;
        }    
        my $psout = `ps -p $parent_id | tail -1 |sed -e's/^ //g'| sed -e's/  */ /g'|cut -d' ' -f4`;
        if ( $psout =~ /firstboot/ ) {
            debug "firstboot IS an ancestor. Set post option.\n";
            $opt{'post'} = 1; 
            return;
        } else {
            # recursive case
            handleFirstBoot($parent_id);
        }    
    }
    
    1 回复  |  直到 10 年前
        1
  •  3
  •   Sobrique    10 年前

    我能提供一个替代的方法吗?从评论来看,你试图解决的问题是启动脚本停滞,因为它正在等待这个脚本返回。

    所以我可以建议 fork() 你的朋友可能在吗?

     my $pid = fork(); 
     if ( $pid ) { 
         exit; 
     }
     sleep $delay_time; 
     do_stuff(); 
    

    将会发生的情况是-您的脚本将被调用,调用者将立即返回,但并行实例将产生并延迟随机延迟间隔-对于加分,这在 cron

    但正如你在评论中所注意到的那样——“好”的解决方案根本不是这样做——我建议看看say, anacron 它在大多数Linux系统上都可用,正是这项特定工作的工具。