简体   繁体   English

从另一个java进程启动的java进程没有&没有按预期工作

[英]A java process launched from another java process without & doesn't work as expected

Suppose a little Java procces whose task is to launch other Java processes. 假设有一个Java procces,其任务是启动其他Java进程。 The procedure is similar to the following: 该过程类似于以下内容:

String[] command = { "/bin/sh", "-c", "some.sh" + " &"};
Process pro = Runtime.getRuntime().exec(command);
//rest

This first option works because the & , and this another one doesn't work: 第一个选项有效,因为& ,而另一个选项不起作用:

String[] command = { "/bin/sh", "some.sh"};
Process pro = Runtime.getRuntime().exec(command);
//rest

Q: What is the meaning of "it doesn't work"? 问:“它不起作用”是什么意思? A: Both options launch the process but in the second one the child process stops working after a few seconds, however, if I inspect running processes ( ps aux | grep some.sh ), it is there (but doing nothing). 答:两个选项都启动了进程,但是在第二个进程中,子进程在几秒后停止工作,但是,如果我检查正在运行的进程( ps aux | grep some.sh ),它就在那里(但什么都不做)。 The first option works fine, it lauches process and the child does its task. 第一个选项工作正常,它启动进程,子进程完成任务。

I don't understand why when I launch child process without background it appears like active in ps processes list but it isn't doing nothing. 我不明白为什么当我在没有背景的情况下启动子进程时,它似乎在ps进程列表中处于活动状态但它没有做任何事情。

Launching a command in Unix with & at the end implies that it will be followed by another command. 使用&在最后用Unix启动命令意味着它将跟随另一个命令。 I presume that if the process is halted and doing nothing, it is likely because it isn't intelligent enough to realize that another command isn't coming. 我认为如果进程停止并且什么也不做,很可能是因为它没有足够的智能来意识到另一个命令没有到来。

Therefore, the reason why the first doesn't close but seems to be doing nothing is precisely because of this added & . 因此,为什么第一次不近,但似乎无所事事的原因也正是因为这一附加& I imagine that some.sh ends. 我想some.sh结束了。 Perhaps it shouldn't, but it is. 也许它不应该,但确实如此。

Please look into Apache Tomcat daemon for information concerning how to create a daemon (under section Unix daemon). 请查看Apache Tomcat守护程序 ,了解有关如何创建守护程序的信息(在Unix守护程序部分下)。 In your code, you should create a shutdown variable and shutdown hook so that when your daemon is halted, you can execute code: 在您的代码中,您应该创建一个shutdown变量和shutdown hook,以便在您的守护程序暂停时,您可以执行代码:

private volatile boolean shutdown = false;

...

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        // What to run on shutdown
        shutdown = true;
    }
});

Once you have this, perform some action every so often in an infinite loop (using sleep of course or your CPU would be wasted): 一旦你有了这个,在无限循环中经常执行一些操作(当然使用睡眠或者你的CPU将被浪费):

while(!shutdowwn) {
    // Perform action here every 1000 milliseconds.
    Thread.sleep(1000);
}

Apache Tomcat daemon can be run on windows as a service or just as well in Linux/Unix. Apache Tomcat守护程序可以作为服务在Windows上运行,也可以在Linux / Unix中运行。 Hope that helps! 希望有所帮助!

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

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