2013-08-29 181 views
-1

我正在使用perl版本5.8.4。检查进程是否正在运行并终止它

我正在使用一个名为JMP的程序。在打开程序之前,我想用perl来检查程序的进程是否已经在运行。如果它正在运行,我想关闭它。

+0

看,这可能帮助ühttp://stackoverflow.com/questions/11273636/check-if-program-is-running -and-run-it-if-in-perl – Developer

+0

$ exists = kill 0,1525; ($存在);打印“进程正在运行\ n”( );从这个你也可以检查 – Developer

+0

这是什么意思0,1525?它如何指向特定的过程? – Vera

回答

1

REWORK:(IDK我怎么到这里来,我只是丢失)

这仅适用于Windows的作品的原因是shell中执行(TASKKILL)。

system('taskkill /F /IM ImageName.exe >nul 2>&1'); 

的可能重复:

How can I kill a program that might not exist from Perl on Win32?

的perl>系统文件:

http://perldoc.perl.org/functions/system.html

TASKKILL文档:

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/taskkill.mspx?mfr=true

关于语法重定向(基于在awnser从How can I kill a program that might not exist from Perl on Win32?):

http://ss64.com/nt/syntax-redirection.html

1

您只需要补充一点:

use autodie 'system'; 
system('killall', '-q', 'JMP'); 

use autodie 'system'; 
system('pkill', 'JMP'); 

如果你要处理的错误检查自己,而不是使用autodie,它看起来像

die "Can't launch killall: $!\n"     if $? < 0; 
die "killall killed by signal ".($? & 0x7F)."\n" if $? & 0x7F; 
die "killall exited with error ".($? >> 8)."\n" if $? >> 8; 
+2

您可能想要添加注释,说明如何检查退出代码以执行其他操作。 – Ryan

+0

原来,OP无论如何都在使用Windows,并忽略告诉我们。 :D –

+0

我注意到了,但他已经有了一个解决方案。 – ikegami

1

使用我在这个问题上从别人那里获得的有用输入,重写答案更适合于这个问题在眼前。

它检查是否正在运行的进程,给你做的比杀更(安慰,如果需要杀死它的子流程的打印输出等)的能力,运行killall如果程序只运行,然后启动jmp

#!/usr/bin/perl 
use warnings; 
use strict; 

# Read all script-name processes 
open PROS, "ps -ef| grep jmp |"; 

# Iterate the processes 
while ($line = <PROS>){ 
    # If we match the process, kill all instances 
    unless ($line =~ m/grep/){ 
     system 'killall jmp'; 
     last; 
    } 
} 

# Finished with the processes 
close PROS; 

# Start jmp 
exec 'nohup /path/to/jmp &'; 

如果你使用的是Windows,你会想看看taskkill而不是killall

+0

我收到一个错误:'ps'不被识别为内部或外部命令, 可操作的程序或批处理文件。 – Vera

+0

@Vera所以你使用Windows?本来有用的问题。 –

相关问题