Reputation: 631
I want to start my program in the background using jsch and 'nohup with &' command. This is my code:
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();
}
As the output I get:
Connected
exit-status: 0
DONE
but the program is not started. Without '&' it works, but with it doesn't. The same situation is when I put nohup command into .sh script and then run it. Any ideas how to solve this problem?
Thanks in advance!
Upvotes: 1
Views: 2591
Reputation: 1
Replace this line:
String command = "sudo nohup -jar [path to my jar] &";
with this:
String command = "sudo nohup -jar [path to my jar]>out.log 2>&1 &";
Upvotes: 0
Reputation: 2053
3 years later...
I've recently had the same problem. I solved it by using:
((ChannelExec)channel).setPty(false);
and by redirecting the output stream. It seems to me it depends on the program being executed. I had a different script that just slept and printed date to a file and it didn't need any redirect. Also it was independent of JSch. Using the command line ssh the problem also existed.
The command I actually wanted to execute needed its output stream redirected away from stdout. If redirecting the stdout alone does not work redirecting the error stream and closing the input stream with <&-
might help.
Upvotes: 0