微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 如何以编程方式在启动它的同一脚本中终止正在运行的进程?

如何以允许我终止它们的方式从脚本启动进程

基本上,我可以轻松地终止主脚本,但终止此主脚本启动的外部进程一直是个问题.我用疯狂搜索Perl 6解决方案.我正准备发布我的问题然后认为我会用其他语言解决问题.

使用Perl 6可以轻松启动外部流程:

my $proc = shell("possibly_long_running_command");

shell在流程完成后返回流程对象.所以,我不知道如何以编程方式找出正在运行的进程的PID,因为在外部进程完成之前甚至不创建变量$proc. (旁注:完成后,$proc.pid返回一个未定义的Any,所以它不会告诉我它曾经有过什么PID.)

以下是一些代码,展示了我创建“自毁”脚本的一些尝试:

#!/bin/env perl6

say "PID of the main script: $*PID";

# limit run time of this script
Promise.in(10).then( {
    say "Took too long! Killing job with PID of $*PID";
    shell "kill $*PID"
} );

my $example = shell('echo "PID of bash command: $$"; sleep 20; echo "PID of bash command after sleeping is still $$"');

say "This line is never printed";

这会导致以下输出终止主脚本,但不会导致外部创建的进程(请参阅Terminated一词后的输出):

[prompt]$./self_destruct.pl6
PID of the main script: 30432
PID of bash command: 30436
Took too long! Killing job with PID of 30432
Terminated
[prompt]$my PID after sleeping is still 30436

顺便说一下,根据顶部,睡眠的PID也是不同的(即30437).

我也不确定如何使用Proc::Async这样做.与shell的结果不同,它创建的异步处理对象没有pid方法.

我最初在寻找Perl 6解决方案,但我对Python,Perl 5,Java或任何与“shell”相互作用的语言的解决方案持开放态度.

解决方法:

对于Perl 6,似乎有Proc::Async模块

Proc::Async allows you to run external commands asynchronously, capturing standard output and error handles, and optionally write to its standard input.

# command with arguments
my $proc = Proc::Async.new('echo', 'foo', 'bar');

# subscribe to new output from out and err handles:
$proc.stdout.tap(-> $v { print "Output: $v" });
$proc.stderr.tap(-> $v { print "Error:  $v" });

say "Starting...";
my $promise = $proc.start;

# wait for the external program to terminate
await $promise;
say "Done.";

方法杀死:

kill(Proc::Async:D: $signal = "HUP")

Sends a signal to the running program. The signal can be a signal name (“KILL” or “SIGKILL”), an integer (9) or an element of the Signal enum (Signal::SIGKILL).

关于如何使用它的示例:

#!/usr/bin/env perl6
use v6;

say 'Start';
my $proc = Proc::Async.new('sleep', 10);

my $promise= $proc.start;
say 'Process started';
sleep 2;
$proc.kill;
await $promise;
say 'Process killed';

如您所见,$proc有一种方法来终止进程.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐