简体   繁体   English

如何使用Perl检查Unix命令何时完成处理

[英]How to use Perl to check when a Unix command has finished processing

I am working on a capstone project and am hoping for some insight. 我正在做一个顶峰项目,并希望获得一些见识。

This is the first time I've worked with Perl and it's pretty much a basic Perl script to automate a few different Unix commands that need to be executed in a specific order. 这是我第一次使用Perl,这几乎是一个基本的Perl脚本,用于自动化一些需要按特定顺序执行的不同Unix命令。 There are two lines throughout the script which executes a Unix command that needs to finish processing before it is acceptable for the rest of the script to run (data will be incorrect otherwise). 脚本中共有两行,它们执行一个Unix命令,该命令需要完成处理,然后脚本其余部分才能运行(否则,数据将不正确)。

How am I able to use Perl (or maybe this is a Unix question?) to print a simple string once the Unix command has finished processing? Unix命令完成处理后,如何使用Perl(或者这可能是Unix问题?)来打印简单的字符串? I am looking into ways to read in the Unix command name but am not sure how to implement a way to check if the process is no longer running and to print a string such as "X command has finished processing" upon it's completion. 我正在研究读取Unix命令名称的方法,但是不确定如何实现一种方法来检查进程是否不再运行,并在完成时打印诸如“ X命令已完成处理”之类的字符串。

Example: 例:

system("nohup scripts_pl/RunAll.pl &");

This runs a command in the background that takes time to process. 这会在后台运行需要花费时间的命令。 I am asking how I can use Perl (or Unix?) to print a string once the process has finished. 我问一个过程完成后如何使用Perl(或Unix?)打印字符串。

I'm sorry if I didn't understand your asking context. 很抱歉,如果我不明白您的询问上下文。 But couldn't you use perl process fork function instead of & if you would like to do parallel process? 但是&如果您想执行并行处理&则不能使用perl进程派生函数代替&呢?

# parent process
if (my $pid = fork) {
    # this block behaves as a normal process

    system("nohup scripts_pl/RunAll2.pl"); # you can call other system (like RunAll2.pl)
    wait; # wait for the background processing
    say 'finished both';
}
# child process
else {
    # this block behaves as a background process
    system("nohup scripts_pl/RunAll.pl"); # trim &
}

You could try to use IPC::Open3 instead of system : 您可以尝试使用IPC::Open3而不是system

use IPC::Open3;
my $pid = open3("<&STDIN", ">&STDOUT", ">&STDERR", 'nohup scripts_pl/RunAll.pl');
waitpid( $pid, 0 );

Or, if you need to run nohup through the shell: 或者,如果您需要通过外壳运行nohup

my $pid = open3("<&STDIN", ">&STDOUT", ">&STDERR", 'bash','-c', 'nohup scripts_pl/RunAll.pl & wait');

Update : Thanks to @ikegami. 更新 :感谢@ikegami。 A better approach if you would like STDIN to stay open after running the command: 如果您希望STDIN在运行命令后保持打开状态,则是一种更好的方法:

open(local *CHILD_STDIN, "<&", '/dev/null') or die $!;
my $pid = open3("<&CHILD_STDIN", ">&STDOUT", ">&STDERR", 'nohup scripts_pl/RunAll.pl');

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

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