简体   繁体   English

Perl调用系统命令并保持脚本同时运行

[英]Perl call a system command and keep the script running at the same time

I am running a perl script that does a logical check and if certain conditions been met. 我正在运行一个执行逻辑检查以及是否满足某些条件的perl脚本。 Example: If it's been over a certain length of time I want to run a system() command on a linux server that runs another script that updates that data. 示例:如果已超过一定时间,我想在运行另一个更新该数据的脚本的linux服务器上运行system()命令。 script that updates the file takes 10-15 seconds, with the current amount of files it has to go through, but can be up to 30 seconds during peak times of the month. 用于更新文件的脚本需要10到15秒的时间,其中包含它必须经过的当前文件数量,但是在一个月的高峰时段最多可能需要30秒。

I want the perl script to run and if it has to run the system() command, I don't want it to wait for the system() to finish before finishing the rest of the script. 我希望运行perl脚本,并且如果它必须运行system()命令,我不希望它在完成脚本的其余部分之前等待system()完成。 What is the best way to go about this? 最好的方法是什么?

Thank you 谢谢

System runs a command in the shell, so you can use all of your shell features, including job control. 系统在外壳中运行命令,因此您可以使用所有外壳功能,包括作业控制。 So just stick & at the end of your command thus: 因此,只需在命令末尾粘贴&即可:

system "sleep 30 &";

Use fork to create a child process, and then in the child, call your other script using exec instead of system. 使用fork创建一个子进程,然后在该子进程中,使用exec而不是system调用其他脚本。 exec will execute your other script in a separate process and return immediately, which will allow the child to finish. exec将在一个单独的过程中执行您的其他脚本并立即返回,这将使孩子完成。 Meanwhile, your parent script can finish what it needs to do and exit as well. 同时,您的父脚本可以完成所需的操作并退出。

Check this out. 检查这个出来。 It may help you. 它可能会帮助您。

There's another good example of how to use fork on this page. 页面上还有一个很好的示例,说明如何使用fork。

Not intended to be a pun due to publication date, but beware of zombies! 由于发布日期而并非双关语,请当心僵尸! It is a bit tricky, see perlipc for details. 这有点棘手,有关详细信息,请参见perlipc However, as far as I understood your problem, you don't need to maintain any relation between the updater and the caller processes. 但是,据我了解您的问题,您无需维护更新程序和调用程序进程之间的任何关系。 In this case, it is easier to just "fire and forget": 在这种情况下,更容易“解雇”:

use strict;
use warnings qw(all);
use POSIX;

# fork child
unless (fork) {
    # create a new session
    POSIX::setsid();

    # fork grandchild
    unless (fork) {

        # close standard descriptors
        open STDIN, '<', '/dev/null';
        open STDOUT, '>', '/dev/null';
        open STDERR, '>', '/dev/null';

        # run another process
        exec qw(sleep 10);
    }

    # terminate child
    exit;
}

In this example, sleep 10 don't belong to the process' group anymore, so even killing the parent process won't affect the child. 在此示例中, sleep 10不再属于该进程的组,因此即使杀死父进程也不会影响子进程。

http://aaroncrane.co.uk/talks/pipes_and_processes/paper.html上有一个很好的教程,介绍如何从Perl运行外部程序(包括运行后台进程)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM