Flushing a SocketChannel before close()
Hi,
I wrote a simple http server using java.nio. I've run into a problem where occasionally, calling close() on the SocketChannel closes the socket prematurely, before all the response bytes have been sent to the client. Is there a way to ensure that the SocketChannel flushes before closing?
Thanks
Yariv
close calls flush.
A socket connect holds data after the connect is closed to ensure data is recieved by the client.
If you want to be really sure the client has recieved data before closing it, send the client a message which causes the client to close the connection.
Similar Messages
-
Non-blocking SocketChannel and close - huh?
It looks like closing a socketchannel that is in non-blocking mode can result in a dead drop of the connection, with some bytes that have already been sent and accepted (as in, 'consumed' from the buffer) being completely dropped.
In fact, I'm generally confused: Actual C non-blocking code has a similar setup for 'close' as you can see in SocketChannel's OP_CONNECT behaviour - just because you want to connect the socket doesn't mean it magically happends without blocking. Wait for a ready flag, then try again.
It should work the same way with close (you try to close, but it may not be possible without blocking).
Is this a huge gaping bug that no one quite figured out just yet, or did I miss something? I loathe to turn on linger, as that's just a crapshoot (you never know if it actually gets through. You could run into funny surprises once the server gets a bit busy. I'd rather not) and tends to cause massive leaks on linux, at least according to some google searches.
There seems to be slightly better performance (in that I have always received all data sofar) if I close the socket instead of the channel (socketChannel.socket().close() instead of socketChannel.close()) - but this has been a random attempt at 'making it work', and I can't find any documentation that backs up that this will DEFINITELY not lose any information without letting me know somehow. That still sounds impossible with this approach.Actual C non-blocking code has a similar setup for
'close' as you can see in SocketChannel's
OP_CONNECT behaviour ...No it doesn't. I don't know what you mean by this.
Closing a socket is asynchronous, but it shouldn't lose any data - if the data can be delivered it will be, followed by the FIN. You don't know when it is delivered, and you don't get to hear about any errors such as an RST coming from the other end, say if it decided to close before reading all the data, or if some intermediate router hung you up.
I'm wondering if you are really dealing with all the short write and zero length write possibilities, i.e. whether the data isn't really still in your output buffer. Don't wish to teach you to suck eggs but there are some subtleties here.
Setting a positive linger timeout doesn't really help because Java doesn't tell you if the timeout expired. (I only asked for this about four years ago). You get to wait while any pending data is delivered, but you still have to guess about whether it all went or the timeout expired, and the behaviour after the timeout expires is platform-dependent: some (Windows) issue an RST, others (Unix) keep trying.
Blocking or non-blocking mode shouldn't make any difference to this (except that Linux will block on a positive linger timeout even in non-blocking mode, which is wrong), and whether you close the channel or the socket is immaterial as one calls the other anyway.
The reason why OP_CONNECT is different in blocking/non-blocking modes is that in blocking mode it won't return until the SYN-ACK is received, while in non-blocking mode it just sends the SYN and relies on you calling connect() again (at the C level) to collect the SYN-ACK, or not - this is what finishConnect() tells you.
tends to cause massive leaks on linux, at least
according to some google searchesIt can't, unless you are referring to the Helix client thing, which appears to be just a badly designed C++ class library with, for some reason, its own linger implementation outside the kernel. -
PS CS6 slow when I close the program: Wait 10 seconds before close.
how i have to do to resolve?
Thank youHello Biromix ,
If its Photoshop CS6,
Please take care of few steps:
1. If its windows :- Uninstall or disable all your third party plugins
2. launch PS with sift key pressed and then press ok.
3. Reset Preferences -
4. Disable visual themes of OS
5. Check your system H/w RAM, GPU, CPU etc
6. Keep your S/w up to date
7. Under preferences -> Performance slide it to 80%, GPU accelleration set it to Basic and Cache to 1.
Check any antivirus or application interference from any other manufacturer.
I think that all you can try to begin with.
Thanks -
JTable question (last edit before close problem)
Hello all,
I have a simple looking problem. It's a JTable inside a dialog, but I can't get exactly the behaviour I want, that is, when the user edits a cell and, without pressing enter or selecting another cell, clicks "OK" (and the dialog hides) the editing should end and the value that was entered to get to the model.
If I show the dialog again, the editing of the cell is still there, and the value is not updated (neither of course shown with a cell renderer)
How could I finish programmatically the editing of a cell, and the result be the same as the user pressed enter or so?
Very very much thank uIt seems I posted this too early, sorry!
I found an answer in
http://forum.java.sun.com/thread.jsp?forum=57&thread=204066 -
Flush file before writing using UTL_FILE
Hi,
Version: 10g
I am using the UTL_FILE.PUT_LINE to write some data into a file.
Now my requirement is to flush this file before every write. Is there a function/procedure which does this?
Require help ASAP.
Thanks in advance.Why flush before a write? The write buffer will be empty. And there will be nothing to flush.
You need to flush after a write in order to flush that write buffer to disk.
You also need to ask yourself why you want to do this? Write caches/lazy writes improve performance. The primary reason for flushing a cache is to ensure that the cache contents are on disk in case the process dies and its dirty unwritten cache is destroyed with it.
Do you expect your process to crash and die? If not, then what other reasons do you think warrants flushing the cache after each write? -
Not flushing changes made in current transaction
I encounter a problem that KODO doesn't flush changes made in current
transaction. I'm using an external transaction manager (JOTM) and XA
datasource (xapool). From the console output, I know I have an active
transaction. According to the KODO automatic flush behaviour
(http://solarmetric.com/Software/Documentation/3.1.2/docs/ref_guide_dbsetup_retain.html),
given kodo.FlushBeforeQueries is true and kodo.ConnectionRetainMode is
transaction, flush should happen before query.
The code is something like this:
userTransaction.begin();
String field1 = "abc";
long field2 = 10L;
String field3 = "123";
Foo foo = new Foo(); // Foo's PK is field1, field2 and field3.
foo.setField1(field1);
foo.setField2(field2);
foo.setField3(field3);
foo1(foo);
Collection foos = foo2(field1, field2);
System.out.println("foos.isEmpty()? : " + foos.isEmpty());
userTransaction.commit();
public void foo1(Foo foo)
PersistenceManager pm = null;
try
pm = getPersistenceManager();
System.out.println("PM.TX: " + pm.currentTransaction() + " active:
" + pm.currentTransaction().isActive());
pm.makePersistent(foo);
catch (ResourceException e)
e.printStackTrace();
finally
if (pm != null && !pm.isClosed())
pm.close();
public Collection foo2(String field1, long field2)
PersistenceManager pm = null;
StringBuffer filter = new StringBuffer();
HashMap parameters = new HashMap();
StringBuffer paramList = new StringBuffer();
Extent ex = null;
Query query = null;
Collection result = null;
Collection result1 = new ArrayList();
Long field2Long = new Long(field2);
try
pm = getPersistenceManager();
System.out.println("PM.TX: " + pm.currentTransaction() + " active:
" + pm.currentTransaction().isActive());
ex = pm.getExtent(Foo.class, true);
filter.append("field1 == paramField1");
filter.append(" && field2 == paramField2");
paramList.append("String paramField1");
paramList.append(" , Long paramField2");
parameters.put("paramField1", field1);
parameters.put("paramField2", field2Long);
query = pm.newQuery(ex, filter.toString());
query.declareParameters(paramList.toString());
result = (Collection) query.executeWithMap(parameters);
catch (ResourceException e)
e.printStackTrace();
finally
if (pm != null && !pm.isClosed())
pm.close();
return result;
From the console,
PM.TX: kodo.runtime.PersistenceManagerImpl@b34b1 active: true
PM.TX: kodo.runtime.PersistenceManagerImpl@b34b1 active: true
foos.isEmpty()? true
If the userTransaction is committed before invoking foo2(), then, the Foo
object is created and foos.isEmpty() returns false.
I am using KODO version: 3.1.2. Here is the kodo.properties:
javax.jdo.PersistenceManagerFactoryClass:
kodo.jdbc.runtime.JDBCPersistenceManagerFactory
javax.jdo.option.Optimistic: true
javax.jdo.option.RetainValues: true
javax.jdo.option.NontransactionalRead: true
javax.jdo.option.ConnectionFactoryName: jdbc/datasource
javax.jdo.option.IgnoreCache: false
kodo.Connection2UserName: <some user>
kodo.Connection2Password: <some password>
kodo.Connection2URL: jdbc:oracle:thin:@<some host>:1521:<some db>
kodo.Connection2DriverName: oracle.jdbc.driver.OracleDriver
kodo.jdbc.DataSourceMode: enlisted
kodo.jdbc.ForeignKeyConstraints: true
kodo.FlushBeforeQueries: true
kodo.ConnectionRetainMode: transaction
kodo.jdbc.VerticalQueryMode=base-tables
kodo.TransactionMode: managed
kodo.ManagedRuntime :
invocation(TransactionManagerMethod=foo.TransactionManagerUtil.getTransactionManager)
kodo.jdbc.DBDictionary : oracle(BatchLimit=0)
Any ideas are appreciated.
Regards,
Willie VuAbe White wrote:
Do you get the same behavior with local transactions?
I don't see anything immediately wrong with your code, but all our internal
tests are passing, and no other user has reported a problem.In a single transaction, I'm using multiple persistence managers which are
closed after usage (method foo1() and foo2() gets different persistence
managers and close them before return). I don't think I can use local
transactions, can I? -
When handling local files , should I call flush() at all?
When handling local files, I am confused by the flush() method.
A lot of tutorial pages say it's safer to call flush() before close(). After thinking for a while, I'm asking mysel: Does flush() applies only to buffered stream(right?)? If a stream is not buffered, program should not call flush(). For buffered stream, the corresponding close() method of the wrapper or stream class should invoke flush() method. If they don't , it's an implementation bug, which should be fixed. So for both buffered and unbuffered stream, no need to call flush() before close()(right?).
Then the question is: when do we need to call flush() method? If we don't need call flush() at all, why are there flush() methods in almost every stream/wrapper class?
Please let me know what is wrong, either me or something else.
Any feedback is appreciated.
Gang"The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream." (Javadoc)
By inheritance this also applies to BufferedOutputStream and its descendants. However FileOutputStream does not extend FOS or BOS so it has nothing to flush(), so flushing it does nothing at any time even before closing.
In general flush() writes buffered bytes out of the JVM into the operating system. When you do have buffering, which in practice you should (e.g. new BufferedOutputStream(new FileOutputStream(...))), you should flush at points when you really want to be rid of the data. When operating on sockets you should always flush before try to read the next data from the socket. You can flush more often if you like but it is often counter-productive. -
Can I close the connection after sending immediately on the server?
I have a C/S program. On the server side, the process as following:
1. accept (blocking)
2. //a connection is established
using a new socket to receive request data from client
3. business processing ... (maybe several seconds)
4. send response data to client
5. close socket immediately
6. listening continuely again
The server side is running on linux and writed by Java, and client is running on windows and writed by C++ Builder.
My problem is:
1. if the server is running on windows, everything is OK.
2. if the server is running on linux (that is exprcted), the client can not receive the response data from server, the client program said the connection is unavailable when he read from socket blockingly.
3. if I add some delay, e.g. 500ms, between sending response and close the connection, the client can receive response normally.
why above?
thanks for help.
JackSorry, long time to go away.
package test.server;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
private int port; // listened port
private ServerSocket ssock; // the server's ip
public EchoServer(String host, int port) {
this.port = port;
// Create a ServerSocket
try {
ssock = new ServerSocket(port);
SocketAddress addr = new InetSocketAddress(host, port);
ssock.bind(addr);
} catch (Exception ex) {
ex.printStackTrace();
new HandleThread().start();
public class HandleThread extends Thread {
public int ntohl(byte[] bytes, int offset) {
int length1 = ((((int) bytes[offset + 0]) << 24) & 0xff000000);
int length2 = ((((int) bytes[offset + 1]) << 16) & 0x00ff0000);
int length3 = ((((int) bytes[offset + 2]) << 8) & 0x0000ff00);
int length4 = ((((int) bytes[offset + 3]) << 0) & 0x000000ff);
return length1 + length2 + length3 + length4;
public void run() {
InputStream in = null;
OutputStream out = null;
try {
while (true) {
System.out.println("Start Listening... [" + port + "]");
Socket clisock = ssock.accept();
//clisock.setSoLinger(true, 1);
System.out.println( "SOLinger:" + clisock.getSoLinger());
try {
System.out.println("Accepted Client Socket... [" + clisock + "]");
in = clisock.getInputStream();
out = clisock.getOutputStream();
// receive four bytes length
byte[] lenbuff = new byte[4];
in.read(lenbuff, 0, 4);
int len = ntohl(lenbuff, 0);
byte[] buff = new byte[len];
in.read(buff, 0, len);
System.out.println("Received length:" + len + " " + new String(buff));
Thread.sleep(1000);
out.write(lenbuff);
out.write(buff);
out.flush();
//Thread.sleep(500);
System.out.println("Send finished。");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
if (out != null) {
try {
out.close();
} catch (Exception ex) {
if (clisock != null) {
try {
long time00 = System.currentTimeMillis();
clisock.close();
System.out.println( "close socket:[" + (System.currentTimeMillis() - time00) + "]");
} catch (Exception ex) {
} catch (Exception ex) {
ex.printStackTrace();
public static void main(String[] args) throws Exception {
if( args.length == 2 ) {
new EchoServer(args[0], Integer.parseInt(args[1]));
} else if( args.length == 2 ) {
new EchoServer("127.0.0.1", Integer.parseInt(args[0]));
} else {
new EchoServer("127.0.0.1", 16000);
}In my application, the package is following:
length(4bytes) + data
I have a simple WinSocket Client, send data to this server and receive the response,the sending is OK, Server can receive all messages.But when client is ready to receive data, the winsock call return WSAECONNRESET(10054).
If I uncomment "Thread.sleep(500);", it means wait some time before close socket, the client can receive all response data.
why? -
Hi everybody,
I need to stop a shutoff browser process before close it (like when we shutdown the Operatin System and there is a modified document opened).
Is there anything like this?
Thanks,
Maur�cio S. Mudrik
IT Director
Intercomax - Your Office in Transit
Cybertools - Tools for Cyber Spaces
Aeroshopping.net - The (future) Brazilian Airports Portal Services
55 11 6445-2399 / 2388 / 2622Yes!
I thinks is this I want.
I gonna test it.
Is there any example?
Thanks.
Maur�cio S. Mudrik
IT Director
Intercomax - Your Office in Transit
Cybertools - Tools for Cyber Spaces
Aeroshopping.net - The (future) Brazilian Airports Portal Services -
Do you want to save changes message while close pdf
hi everyone...
I am very new to PDF programming
basically I wrote my program in notepad and I saved it as .pdf format
but when I open it and try to close it..it showing me pop up like do you want to save changes..which is I dont want to happen...
is any one have idea what changes i have to do or how i make my file readonly....
thnks in advance...thanks Irosenth,
Well my requirement is very small.....
I am not using many XObjects In my program except one which is for Image
ok Following code , I copied from PDF refe tutorials. Even that is also not working(Asking me for Save before close).. can anyone correct xref to avoid that error
%PDF-1.4
1 0 obj
<< /Type /Catalog
/Outlines 2 0 R
/Pages 3 0 R
>>
endobj
2 0 obj
<< /Type /Outlines
/Count 0
>>
endobj
3 0 obj
<< /Type /Pages
/Kids [4 0 R]
/Count 1
>>
endobj
4 0 obj
<< /Type /Page
/Parent 3 0 R
/MediaBox [0 0 612 1000]
/Contents 5 0 R
/Resources << /ProcSet 6 0 R >>
>>
endobj
5 0 obj
<< /Length 883 >>
stream
% Draw a black line segment, using the default line width.
150 250 m
150 350 l
S
% Draw a thicker, dashed line segment.
4 w% Set line width to 4 points
[4 6] 0 d% Set dash pattern to 4 units on, 6 units off
150 250 m
400 250 l
S
[] 0 d% Reset dash pattern to a solid line
1 w % Reset line width to 1 unit
% Draw a rectangle with a 1-unit red border, filled with light blue.
1.0 0.0 0.0 RG% Red for stroke color
0.5 0.75 1.0 rg% Light blue for fill color
200 300 50 75 re
B
% Draw a curve filled with gray and with a colored border.
0.5 0.1 0.2 RG
0.7 g
300 300 m
300 400 400 400 400 300 c
b
endstream
endobj
6 0 obj
[/PDF]
endobj
xref
0 7
0000000000 65535 f
0000000009 00000 n
0000000074 00000 n
0000000120 00000 n
0000000179 00000 n
0000000300 00000 n
0000001532 00000 n
trailer
<< /Size 7
/Root 1 0 R
>>
startxref
1556a
%%EOF
xref
5 1
0000000179 00000 n
trailer
<<
/Root 1 0 R
>>
thanks in advance. -
Hi,
I want to close a document and reopen it immediately. I am using SDKLayoutHelper methods to open and close a document. But closing a document with kProcess always crashes. I tried various methods(IDocumentCommands, ProcessScheduledCommands) to make it work but everytime it crashes.
Can anybody suggest me what is the right way to close and reopen the document immediately?
I am using InDesign CS4.
Thanks,
VSP
P.S. I am able to close and reopen by scheduling the commands.Hi,
I tried the following code and it crashes.I have taken the BasicMenu sample and tried to close the current active document.
As per the previous reply from Dirk I reset the docPtr before close. This is to remove the reference to the document.
Thanks,
VSP
void BscMnuActionComponent::DoAbout()
InterfacePtr<IDocument> docPtr(GetExecutionContextSession()->GetActiveContext()->GetContextDocument(), UseDefaultIID());
UIDRef documentUIDRef = ::GetUIDRef(docPtr);
InterfacePtr<IDocFileHandler> docFileHandler(Utils<IDocumentUtils>()->QueryDocFileHandler(documentUIDRef));
if (!docFileHandler)
return;
if (docFileHandler->CanClose(documentUIDRef))
docPtr.reset();
docFileHandler->Close(documentUIDRef, kSuppressUI, kTrue, IDocFileHandler::kProcess); // Tried with kFullUI and it crashes. -
How to open the file writer for next entry after stream is close?
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class TryOut {
public static void main(String args[]) throws IOException{
int inputQuestionnAireNum = 0;
int inputPostCode = 0;
int inputGender = 0;
int inputAge = 0;
int x=0;
Scanner input = new Scanner(System.in);
FileWriter fwrite = new FileWriter("tryout.txt", true);
BufferedWriter out = new BufferedWriter(fwrite);
boolean invalidNum = false;
do{
System.out.print("1 new entry or 0 print");
x = Integer.parseInt(input.nextLine());
if(x == 1)
//Questionnaire Number
System.out.print("Enter Questionnaire Number [ ] ");
inputQuestionnAireNum = Integer.parseInt(input.nextLine());
out.write("NumBER OF Q: "+inputQuestionnAireNum+", ");
//Postal code
System.out.print("Enter Postal Code [ ] ");
inputPostCode = Integer.parseInt(input.nextLine());
out.write("PostCode: "+inputPostCode+", ");
//Age
System.out.print("Enter Age [ ] ");
inputAge = Integer.parseInt(input.nextLine());
out.write("Age: "+inputAge+", ");
//Gender
System.out.print("Enter Gender '1' for Male and '2' for for female [ ] ");
inputGender = Integer.parseInt(input.nextLine());
out.write("Gender: "+inputGender+", \n");
out.close();
} while(x != 0);
Result:
1 new entry or 0 print1
Enter Questionnaire Number [ ] 2
Enter Postal Code [ ] 1
Enter Age [ ] 3
Enter Gender '1' for Male and '2' for for female [ ] 4
1 new entry or 0 print1
Enter Questionnaire Number [ ] 2
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedWriter.ensureOpen(BufferedWriter.java:98)
at java.io.BufferedWriter.write(BufferedWriter.java:203)
at java.io.Writer.write(Writer.java:126)
at TryOut.main(TryOut.java:31)
Hi, how can i open the file writer stream again for next entry after it is has been closed? if i do not close(); all my entry will not be recorded to the text file. how can i solve this ?
Edited by: metaroot on Feb 18, 2008 6:39 PMThe short answer to your question: use out=new BufferedWriter(fwrite) inside the do loop as well.The only difference that would make would be to make the problem worse. It is poor practice. Stream stacks should be constructed once for the life of the stream.
What he needs to do is close his stream outside the loop, possibly calling flush() where he presently has close().
The more relevant answer is: Why are you not wrapping the user-friendly PrintWriter class, wrapping it around the BufferedWriter?Possibly because he doesn't like the fact that PrintWriter swallows exceptions? which makes it less user-friendly IMO.
The println and print methods are very useful, and do not need closing between loop iterations.Neither does anything else.
By the way,you say that without a close() the BufferedWriter doesn't output to the file.I don't know: I never used/tried it.Even if it doesn't, it will surely output after you come out of the loop.If you don't want to use a PrintWriter, why don't you investigate this?Posting guesses here isn' t really much help, especially about something you've never used. A BufferedWriter has a buffer and it doesn't write anything until the buffer is full, you flush it, or your close it. -
Sok.close() vs. objOutStream.close
sok.close()completely closes the Socket.
while:
objOutputStream.close()leaves the Socket open. and it just
unbinds whatever serial stream is bound to on the other
end of the socket. right?
write host
ObjectOutputStream oos = new ObjectOutputStream(sok.getOuputStream());
oos.writeObject((List<String>) myList);
oos.close(); // does NOT close the socket
ObjectOutputStream oos2 = new ObjectOutputStream(sok.getOuputStream());
oos2.writeObject((List<String>) anotherList);
read host
Socket sok = serverSocket.accept();
while(true) {
ObjectInputStream ois = new ObjectInputStream(sok.getInputStream());
List<String> someList = (List<String>) ois.readObject();
.... // do i need to call ois.close()? i'm confused.
}basically, i just want a pool of open Sockets.
and NOT a pool of ObjectOutputStreams
thare binded to a corresponding ObjectInputStream
thanks.> sok.close()> completely closes the Socket.Correct
while:
> objOutputStream.close()> leaves the Socket open.
Wrong. It flushes the ObjectOutputStream and closes the Socket. Because of the flush, this is how you should be closing the stream and the socket.
and it just unbinds whatever serial stream is bound to on
the other end of the socket. right?Wrong. I don't even know that this means.
oos.close(); // does NOT close the socketWrong. It does.
ObjectOutputStream oos2 = new
ObjectOutputStream(sok.getOuputStream());This will fail with an IOException. As you would have discovered when you tried it. If you tried it. Which evidently you haven't.
.... // do i need to call ois.close()? i'm confused.Only when you want to close the socket.
basically, i just want a pool of open Sockets.
and NOT a pool of ObjectOutputStreams
thare binded to a corresponding
ObjectInputStream
Bad luck. You have to have both. -
How To: Use Shutdown thread to flush Java Logger.
I use the Java Logger as follows:
Logger log = Logger.getLogger("company-name-here");but notice that when exiting the application the last few messages are not printed out
to the log, even if I put a one second delay in the applications Shutdown Hook.
I want to get every single log message before the JVM is allowed to shut down,
would anyone know of a way to do this? Could you for example attach a
LogHandler to flush the messages?
Thank.But I've got two shutdown hooks associated with this application
In both I log a message when the shutdown hook starts, AND another when it finishes.
In the best case I might see both Shutdown hooks start messages, but I've not seen
the "shutdown hook is finished" log in the dozen times I've looked for it.Note that the logging framework probably has its own shutdown hook, to flush buffered messages before stopping logging: javax.logging certainly has one, as witnessed in a recent thread .
Shutdown hooks are threads objects, and as per the API javadoc +"the virtual machine (...) will start all registered shutdown hooks in some unspecified order and let them run concurrently"+, so you may very well have an unfortunate scheduling where the logging is stopped before the "last" log messages get through.
The library may refuse the last log messages with an exception (see the thread linked above), but you have no guarantee of even being notified of that (check the err output of the first process).
Thus my question. These log messages are going to a Swing window in another
application, so it is possible that maybe something about the inter-process
communication that gets shutdown prematurely.And to reduce the list of suspects, you should try if possible to eliminate this possibility, by experimenting with a plain-old file- or console-targetted logger, that does not run through this "remote logging" machinery.
Good luck.
J. -
I want to execute [b]some shell [/b]commands in a java program
Hello,
I would like to know if it's possible to execute some unix commands in the same "environment"... I mean, if I use the exec() function to execute the "cd /tmp" command, and after that, if I want to do "ls" , I'm not in the "/tmp" directory, know what I mean ??
In fact, I want to have in my GUI a textarea or something like that, in which one can enter several unix command like in a xterm window...
I don't know how to do that and if it's possible ??
Thank you very much for your answers !OK !! It works with this code but I don't understand why I have to do "return" twice before the command execute ??
(I'm a newbie)
Here's the sample code:
import java.io.*;
public class Tonta {
private String dada="";
private BufferedReader in;
private InputStream instr;
private InputStream errstr;
private PrintStream outstr;
private Process transyt;
private Tonta t;
public Tonta() {
//Executem el programa
try {
transyt=Runtime.getRuntime().exec("ksh");
System.out.print("toto");
} catch (IOException e)
{System.out.println("EXCEPCION:exec"+ e.getMessage());}
instr= transyt.getInputStream();
errstr= transyt.getErrorStream();
outstr= new PrintStream(transyt.getOutputStream());
in = new BufferedReader( new InputStreamReader(System.in));
}//end of constructor
public void run() {
int exit=0;
boolean processEnded= false;
try {
while (!processEnded) {
try {
exit = transyt.exitValue();
processEnded = true;
catch (IllegalThreadStateException e) {}
System.out.print("\nREMOT:");
System.out.flush();
int n= instr.available();
if (n>0) {
byte[] pbytes= new byte[n];
instr.read(pbytes);
System.out.print(new String(pbytes));
System.out.flush();
n= errstr.available();
if (n>0) {
byte[] pbytes= new
byte[n];
errstr.read(pbytes);
System.err.print(new
String(pbytes));
System.err.flush();
System.out.println();
System.out.print("LOCAL> ");
System.out.flush();
dada= in.readLine();
if (dada.equals("exit")) {
System.out.println();
System.out.println("Programa finalizado");
System.out.flush();
transyt.destroy();
instr.close();
errstr.close();
outstr.close();
System.exit(0);
outstr.println(dada);
outstr.flush();
try {
Thread.sleep(10);
catch (InterruptedException e) {}
System.out.println();
System.out.println("Process exited with:"+ exit);
System.out.flush();
} catch (IOException e) {
System.err.println("EXCEPCION "+ e.getMessage());
public static void main (String [] args) {
Tonta t= new Tonta();
t.run();
}Thanks
Maybe you are looking for
-
FIXED: DVI-to-Video Adapter + Windows
For those interested, please see: http://discussions.apple.com/thread.jspa?threadID=1266844&tstart=0 This might fix other DVI-output issues too.
-
To find Queries by InfoObjects
Hi SDN Community Here is a reversal of a post made by another developer List of infoobjects used in a Query This has the reverse logic... thanks for the tip. *& Report ZBW_FIND_CHARACTERISTICS_QUERY SAP Consulting BW Tools: *& Find Characteristics i
-
Hello, CanI set up two accounts for two different iPhones on the same iTunes account. Thanks JIMMY
-
Employee determination in an account from Territory.
Hi everyone, We have a requirement in one of our projects where while we create an account, system should pick-up the employees for each of the relationship categories from "Territory Management". We have done this for Transactions but not for Master
-
Converting and combining files to scale
I am trying to combine files for a pattern I am selling. The converter correctly sizes the word document to 8.5 x 11" but the pattern pieces with the drawings show up as much larger, like 11 x 15", so that when you try to print them to scale (100%) ,