Skip to content
Advertisement

Kill process before disconnecting

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?

Advertisement

Answer

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);
  }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement