1 Reply Latest reply on May 7, 2004 5:21 PM by 843810

    Bad File Descriptor exception...

    843810
      Ok, here's the problem:

      I run a perl script in java using the Runtime.exec(String command) method, I hand this process to a thread which gets the InputStream from the process, and reads it byte by byte. Each time it reads a byte I immediately write that byte to the file in a syncronized block of code. Meanwhile, outside of this thread I wait until the process completes execution using the Process waitFor() method, then I close the output stream I was using for writing to the file.

      This does not work properly and I can not figure out why. It usually only finishes writing out half or less than half the file until I get an error reading Bad File Descriptor. Here is the error and the code, any suggestions as to why this doesn't work would be greatly appriciated...

      java.io.IOException: Bad file descriptor
      at java.io.FileOutputStream.writeBytes(Native Method)
      at java.io.FileOutputStream.write(FileOutputStream.java:260)
      at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:66)
      at java.io.BufferedOutputStream.write(BufferedOutputStream.java:79)
      at edu.utexas.arlut.spars.libs.util.ProcessOutFile$InputStreamFile.run(ProcessOutFile.java:60)

      public class ProcessOutFile
      {
           private InputStreamFile m_std;
           private InputStreamFile m_err;


           public ProcessOutFile(Process proc, BufferedOutputStream out)
           {
                m_std = new InputStreamFile(new BufferedInputStream(proc.getInputStream()), out);

                m_std.start();

      try {
      proc.waitFor();
      out.close();
      } catch ( Exception e ) {
      e.printStackTrace();
      }
           }

           class InputStreamFile extends Thread {
           private final BufferedInputStream m_in;
           private BufferedOutputStream out;
      StringBuffer tempBuffer = new StringBuffer();

      public InputStreamFile(BufferedInputStream in, BufferedOutputStream out)
           {
           m_in = in;
           this.out = out;
           }

      public void run()
           {
           int nextByte;
           
           try
           {
           while (true)
           {
           nextByte = m_in.read();
           
           if (nextByte == -1)
           {
           break;
           }
           
           synchronized (this)
           {

      out.write((char)nextByte); // Line 60
           }
           }
           }
           catch (Exception e)
           {
      e.printStackTrace();
           }
           }
           }
      }