java.io.EOFException when serialize object from ch

2019-09-21 04:45发布

问题:

I am creating a new process using java ProcessBuider and I want an object to be sent to the parent from the creating child. Here, I serialize the object from child side and send it to the parent. But when I read the sent object from parent, there is an exception saying

java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)

Felt like still there are no streams receive to the parent when I am trying to read that.Parent, Child and the Sending object java files are detailed below.

DTO.java

public class DTO implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;

    public DTO(String name)
    {
        this.name = name;
    }

    public String getName() {
        return name;
    }

@Override
    public int hashCode() {}

@Override
public boolean equals(Object obj) {}

Parent.java

public class Parent {

  public static void main(String[] args) {

      try {
          new Parent().start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

      public void start() throws IOException, InterruptedException, ClassNotFoundException
      {
            String classpath = System.getProperty("java.class.path");
            String className = Child.class.getCanonicalName();

            ProcessBuilder builder = new ProcessBuilder(
                "java", "-cp", classpath, className);

            builder.inheritIO();
            Process process = builder.start();

            if (process.isAlive()) {

                ObjectInputStream input = new ObjectInputStream(process.getInputStream());
                DTO dto = (DTO)input.readObject();
                System.out.println();

            }
      }
}

Child.java

public class Child {

    public static void main(String[] args) throws IOException {
        DTO dto = new DTO("text");

        ObjectOutputStream stream = new ObjectOutputStream(System.out);
        stream.writeObject(dto);
        stream.flush();
        stream.close();
    }
}

What is the wrong that I am doing here ? Any suggestions to fix this

回答1:

This starts working when you remove the builder.inheritIO(); code segment from parent where removing that indicates both child and parent will no longer shared a common standard I/O. Both child and parent will have different standard I/Os