java一段时间后杀掉进程
我的代码是这样的:
Runtime rt = Runtime.getRuntime();
// cmd == "cmd.exe /C java =Xms2M =Xmx16M Sth"
Process proc = rt.exec(cmd);
现在我想在一秒钟后终止这个进程,并将他的输出和错误放入字符串变量中。
怎么办呢?
就我而言: 我在已编译的类 Sth 中有一个不定式循环。我正在启动它,然后,一秒钟后我想杀死它。
//我先在 Win XP 上测试,然后在 Debian 上测试。
谢谢 齐姆
my code goes like this:
Runtime rt = Runtime.getRuntime();
// cmd == "cmd.exe /C java =Xms2M =Xmx16M Sth"
Process proc = rt.exec(cmd);
Now i want to kill this process after a second, and get his output and error into a string variables.
How to do that ?
In my case:
I have a infinitive loop in compiled class Sth. I'm starting it and then, after one second i want to kill it.
//I'm testing it on Win XP then Debian.
thx
Tzim
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这会有点棘手,因为一旦终止进程,它的输出就不再可用,所以你必须在杀死它之前获取输出。
这是假设该进程在此期间不会自行关闭。如果是这样,InputStream 将无法使用,您会希望自己一直在读取数据而不是无所事事。
您肯定希望使此异常安全 - 将调用
proc.destroy
放入finally 处理程序中,以确保子进程被终止。It will be a little tricky because once you terminate the process, its output is no longer available, so you have to grab the output before you kill it.
This is assuming that the process doesn't close itself in the meantime. If it does, the InputStream will not be available for use, and you'll wish you had been reading the data instead of twiddling your thumbs.
You'll definitely want to make this exception-safe — put the call to
proc.destroy
in a finally handler to ensure that the child process gets terminated.(你的cmd中有一个拼写错误,你写了“=Xms2M”而不是“-Xms2M”,“-Xmx16M”也是如此)。
永远不要像这样调用 Runtime.exec:您必须将“cmd”拆分到一个数组中,否则您会遇到很多问题。这样做:
(You have a typo in your cmd, you wrote "=Xms2M" instead of "-Xms2M", same for "-Xmx16M").
Never call Runtime.exec like that: you must split your 'cmd' in an array or you'll encounter lots of issues. Do it like this:
您可以使用 ProcessBuilder 返回一个 Process 对象并使用它的destroy() 方法。
示例
You can use ProcessBuilder which returns a Process object and use it's destroy() method.
Example
这也可能对您有所帮助:
This might also help you out: