我正在使用 sshj 并试图跟踪一个文件,但我的问题是远程进程永远不会被终止。
在下面的示例代码中,您可以看到我尝试跟踪/var/log/syslog,然后向进程发送终止信号。然而,在应用程序停止并且我列出服务器上的所有进程后,我仍然可以看到一个 Activity 的尾进程。
为什么这段代码不会终止进程?我可以做些什么来补救?
SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier(new PromiscuousVerifier());
try {
ssh.connect("localhost");
ssh.authPassword("xxx", "xxx");
final Session session = ssh.startSession();
try {
final Command cmd = session.exec("tail -f /var/log/syslog");
cmd.signal(Signal.KILL);
System.out.println("\n** exit status: " + cmd.getExitStatus());
} catch (IOException e) {
e.printStackTrace();
}finally{
session.close();
}
} finally{
ssh.disconnect();
}
编辑
还尝试发送所有可用信号。
for(Signal s : Signal.values()){
cmd.signal(s);
}
最佳答案
分配 PTY 并发送 Ctrl+C 字符代码对我有用:
final Session session = ssh.startSession();
session.allocateDefaultPTY();
try {
final Command cmd = session.exec("tail -f /var/log/syslog");
// Send Ctrl+C (character code is 0x03):
cmd.getOutputStream().write(3);
cmd.getOutputStream().flush();
// Wait some time for the process to exit:
cmd.join(1, TimeUnit.SECONDS);
// If no exception has been raised yet, then the process has exited
// (but the exit status can still be null if the process has been killed).
System.out.println("\n** exit status: " + cmd.getExitStatus());
} catch (IOException e) {
e.printStackTrace();
}finally{
session.close();
}
当然,能发信号就更好了,但如果连OpenSSH服务器都不支持,那就没希望了:/
关于java - 通过sshj杀死一个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7330692/