I am using Jsch to tail a server-log. When I close my exec-channel and session, the "tail -f ..." process still stays alive at server side.
I tried to do channel.sendSignal("KILL")
but it throws an exception:
com.jcraft.jsch.JSchException: failed to send channel request
how can I do a clean disconnect?
“ kill -9” command sends a kill signal to terminate any process immediately when attached with a PID or a processname. It is a forceful way to kill/terminate a or set of processes. “ kill -9 <pid> / <processname>” sends SIGKILL (9) — Kill signal. This signal cannot be handled (caught), ignored or blocked.
pid is the process ID of the recipient. If pid is greater than 0, kill sends a signal to a process whose ID equals pid . If pid is 0, kill sends the signal to all processes whose process group ID is equal to that of the sender, for which the sender has the necessary privileges to send a signal.
Basically, the kill -15 is a term signal, which the process could catch to trigger a graceful shutdown, closing pipes, sockets, & files, cleaning up temp space, etc, so to be useful it should give some time. The -9 is a kill and can't be caught.
I know this is an old post but I'm posting my solution in case someone needs it.
After some testing I learned that I had to send the int value of the signal instead of the string:
channel.sendSignal("2"); // CTRL + C - interrupt
channel.sendSignal("9"); // KILL
For more signals scroll to 'Standard signals' on this page.
I'm using the following methods to send and interrupt commands. They are slightly modified versions of the example found here.
public String sendCommand(String command)
{
StringBuilder outputBuffer = new StringBuilder();
try
{
Channel channel = sesConnection.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.connect();
InputStream commandOutput = channel.getInputStream();
int readByte = commandOutput.read();
while(readByte != 0xffffffff)
{
outputBuffer.append((char)readByte);
readByte = commandOutput.read();
if (interrupt)
{
interruptChannel(channel);
break;
}
}
channel.disconnect();
}
catch(IOException ioX)
{
logWarning(ioX.getMessage());
outputBuffer.append(ioX.getMessage());
return null;
}
catch(JSchException jschX)
{
logWarning(jschX.getMessage());
outputBuffer.append(jschX.getMessage());
}
finally
{
setInterrupt(false);
}
return outputBuffer.toString();
}
private void interruptChannel(Channel _channel)
{
try
{
_channel.sendSignal("2");
}
catch (Exception e)
{
logger.error("Failed interrupting channel", e);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With