我想使用 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();
}
作为我得到的输出:
Connected
exit-status: 0
DONE
但程序没有启动。没有'&'它可以工作,但没有它。同样的情况是当我将 nohup 命令放入 .sh 脚本然后运行它时。任何想法如何解决这个问题?
提前致谢!