Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!eternal-september.org!feeder.eternal-september.org!aioe.org!.POSTED!not-for-mail From: Steven Simpson Newsgroups: comp.lang.java.programmer Subject: Re: [Windows] Any way to distinguish ^C Induced EOF from ^Z EOF? Date: Tue, 13 Mar 2012 17:26:27 +0000 Organization: Aioe.org NNTP Server Lines: 53 Message-ID: <3jc439-dc4.ln1@s.simpson148.btinternet.com> References: NNTP-Posting-Host: krWlnDe2fr2s4PvVwNqSrw.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-15; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:10.0.2) Gecko/20120216 Thunderbird/10.0.2 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:12974 On 13/03/12 13:11, Jan Burse wrote: > Its a custom made wrapper for Signal & SignalHandler. > In version 1 of the above class I used the package > sun.misc.*. In version 2 of the above class I > used reflection i.e. Proxy class etc.. It will > noop when sun.misc.Signal is not present. I was going to suggest using Runtime.addShutdownHook(Thread) as a portable alternative. You don't find out which signal was raised, but it gives your program a chance to shut down gracefully instead of abruptly. import java.io.*; public class TestInput { public static void main(String[] args) throws Exception { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { Thread.sleep(10 * 1000); } catch (InterruptedException ex) { } } }); FileInputStream fs = new FileInputStream(FileDescriptor.in); byte[] buf = new byte[256]; for (;;) { System.out.print("test: "); int len = fs.read(buf); String str = new String(buf,0,Math.max(0,len)); System.out.println("len = "+len+", buf = "+str+", buf[0]="+buf[0]); if ("exit".equals(str.trim())) break; } } } Unfortunately, you still get the same read()==-1 on Windows, while the read call doesn't return on Linux. Of course, this loop doesn't terminate on EOF, and while the shutdown hook is still running, you can continue to type on both Windows and Linux, and have the results printed. However, this could be a way to distinguish the 'fake' EOF from a real one. Having received -1, read again. A real one will produce -1 again, but the fake one will block or yield more input. For a real EOF, the behaviour seems the same on Windows and Linux, so stop when you get two '-1's. Can't speak for Mac, or anything else, of course. Is a read() call's behaviour well defined after a previous call returned -1? I couldn't tell from a quick scan of the docs. -- ss at comp dot lancs dot ac dot uk