[英]jsch & nohup - program doesn't start
我想使用 jsch 和 'nohup with &' 命令在后台启动我的程序。 这是我的代码:
String command = "sudo nohup -jar [path to my jar] &";
try{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setPty(true);
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
} catch(Exception e) {
e.printStackTrace();
}
作为 output 我得到:
Connected
exit-status: 0
DONE
但程序没有启动。 没有 '&' 它有效,但没有它。 同样的情况是当我将 nohup 命令放入 .sh 脚本然后运行它时。 任何想法如何解决这个问题?
提前致谢!
三年后...
我最近有同样的问题。 我通过使用以下方法解决了它:
((ChannelExec)channel).setPty(false);
并通过重定向输出流。 在我看来,这取决于所执行的程序。 我有一个不同的脚本,它只是将日期和日期打印到文件中,不需要任何重定向。 它也独立于JSch。 使用命令行ssh也存在此问题。
我实际上想要执行的命令需要将其输出流重定向到stdout之外。 如果仅重定向标准输出不起作用,则重定向错误流并使用<&-
关闭输入流可能会有所帮助。
替换这一行:
String command = "sudo nohup -jar [path to my jar] &";
有了这个:
String command = "sudo nohup -jar [path to my jar]>out.log 2>&1 &";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.