I'm trying to execute a script in background with nohup
and want to disconnect without reading output. Is it required to get and read input stream channel.getInputStream(); in.read(...)
in this case?
It is a long running script and I want get control back ASAP. If reading InputStream
is required, how to get control back ASAP without waiting for long.
String command = "nohup script.sh > /home/user1/output.txt 2>&1 &";
session.connect();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
in.read(...)
channel.disconnect();
session.disconnect();
You need to wait until the command completes. Reading the input stream until it closes is the most safe way to do that in JSch.
See Running command using "exec" channel with JSch does not return any output
In your case, as your command cannot have any output (so it cannot hang if you do not read the output), you can achieve the same by simply by looping until channel.isClosed()
is true. But I'd stick with the standard approach with reading the output, as you never know when someone will change the command, not knowing that your waiting code is designed specifically for commands that have no output.