我想使用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脚本中,然后运行它。有什么办法可以解决这个问题吗?
提前感谢!
发布于 2015-11-30 23:59:32
三年后...
我最近也遇到了同样的问题。我通过使用以下命令解决了这个问题:
((ChannelExec)channel).setPty(false);以及通过重定向输出流。在我看来,这取决于正在执行的程序。我有一个不同的脚本,它只是睡眠并将日期打印到一个文件中,它不需要任何重定向。而且它是独立于JSch的。使用命令行ssh也存在这个问题。
我实际上想要执行的命令需要将其输出流重定向到远离stdout。如果仅重定向标准输出不起作用,重定向错误流并使用<&-关闭输入流可能会有所帮助。
发布于 2021-10-06 09:06:20
替换此行:
String command = "sudo nohup -jar [path to my jar] &";有了这个:
String command = "sudo nohup -jar [path to my jar]>out.log 2>&1 &";https://stackoverflow.com/questions/12408243
复制相似问题