The tail -f process will not end after closing the JSch connection

I used JSch to write the file to a remote computer. But I found that after the program exits, the tail -f process is still present on the remote computer. if I remove the -f option, everything will be OK.

I tried to use "sendSignal ()", but it does not work. It seems that the OpenSSH function is not implemented.

Here is the testing code.

public static void main(String[] args) throws Exception { String usr = args[0]; String host = args[1]; String password = args[2]; JSch jsch = new JSch(); Session session = jsch.getSession(usr, host); String pwd = password; session.setPassword(pwd); Hashtable<String, String> config = new Hashtable<String, String>(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(15000); session.setServerAliveInterval(15000); ChannelExec m_channelExec = (ChannelExec) session.openChannel("exec"); String cmd = "tail -f /var/log/messages"; m_channelExec.setCommand(cmd); InputStream m_in = m_channelExec.getInputStream(); m_channelExec.connect(); BufferedReader m_bufferedReader = new BufferedReader(new InputStreamReader(m_in)); int i = 0; while (++i < 10) { if (m_bufferedReader.ready()) { String line = m_bufferedReader.readLine(); System.out.println(line); } Thread.sleep(1000); } m_bufferedReader.close(); m_channelExec.sendSignal("SIGINT"); m_channelExec.disconnect(); session.disconnect(); System.out.println("exit"); } 

Is there any solution to solve this problem?

+4
source share
1 answer

The execCommand command does not allocate the control tty for the channel, so the tail actually writes to the channel. It will continue until more data is sent to it (it will receive SIGPIPE).

The simplest solution is to use tty-use:

 m_channelExec.setPty(true); 

In the line before m_channelExec.connect();

Which should give you the desired behavior.

+2
source

All Articles