杀死Linux进程刚跑
问题描述:
tail -f test.log
上面的命令将尾部,其运行的幕后过程日志。我怎样才能杀死那个特定的进程?杀死Linux进程刚跑
我可以在shell上按“Ctrl-Z”,但是我正在使用Java运行该命令,并且需要终止该进程。
对此的任何帮助将不胜感激。
感谢
答
当你start a subprocess with Java回传对应于正在运行的进程a Process
object 。您可以使用destroy()
method on the Process
object来终止运行命令。
所以,你会启动它:
Process p = Runtime.getRuntime().exec(new String[] {"tail","-f","test.log"});
,并杀死它:
p.destroy();
如果你只是读出新的行添加到文件,你有没有考虑本身在做这个Java的?读取该文件是非常简单的:
try {
BufferedReader input = new BufferedReader(new FileReader("tail.log"));
while (true) {
String line;
while ((line = input.readLine()) != null) {
//You'll probably want to do something other than println()
System.out.println(line);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
input.close();
}
catch (IOException ioe) {
//Handle this
}
你可能会想在另一个Thread
运行此。与tail -f
不同,上述代码不处理从头开始重写的文件,而不是附加到,但您可以修复该问题。
答
好了,你可以做
ps -ef | grep java
找到所有的java进程,然后杀了你想要的。
答
你可以尝试一个killall tail
,但这会杀死所有正在运行的尾部进程。
的更好的方法是使用返回Process
:http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html
一旦你有
Process child = Runtime.getRuntime().exec("tail -f test.log");
可以
child.destroy()