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

Is there a better way to detect that my Perl script was called from "firstboot"?

我有一个 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);
    }    
}

我可以提供另一种方法吗 - 根据评论,您试图解决的问题是启动脚本停滞,因为它正在等待这个 return。

那么我可以建议 fork() 可能是你的朋友吗?

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

将会发生的事情是 - 您的脚本将被调用,调用者将立即 return,但并行实例将产生并延迟随机延迟间隔 - 对于奖励积分,这将同样有效在 cron 也是。

但是正如您在评论中似乎注意到的那样 - 'good' 解决方案根本不是那样做 - 我建议看看说,anacron 大多数情况下都可用Linux 系统正是完成这项特定工作的工具。