2

I am trying to run mysql to execute some files from java. The input is read from a file and should be piped into the mysql process, everthing seems ok but the line

int exitCode = proc.waitFor(); 

never returns.

private boolean runScript(String path, String cmd, File file) throws IOException, InterruptedException {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec( path + File.separatorChar + cmd );
        OutputStream procOS = proc.getOutputStream();
        InputStream procES = proc.getErrorStream();
        InputStream procIS = proc.getInputStream();
        OutputStreamWriter procStdIn = new OutputStreamWriter( procOS );

        FileInputStream fis = new FileInputStream( file );
        BufferedReader reader = new BufferedReader( new InputStreamReader( fis ) );
        String send;

        while ( ( send = reader.readLine() ) != null ) {
            procStdIn.write( send );
            System.out.println( send );
            copyStream( procES, System.err );
            copyStream( procIS, System.out );
        }
        procStdIn.write( "\r\nexit\r\n" );
        int exitCode = proc.waitFor();
        return exitCode == 0;
    }

    private void copyStream(InputStream is, PrintStream err) throws IOException {
        byte b[] = new byte[ 1024 ];
        int length;
        while ( is.available() > 0 && ( length = is.read( b ) ) > 0 ) {
            err.write( b, 0, length );
        }

}

stacker
  • 68,052
  • 28
  • 140
  • 210

2 Answers2

3

I suspect you're blocking reading stdout and stderr. See this answer for more details.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

Add:

procStdIn.flush();

after:

procStdIn.write( "\r\nexit\r\n" );
Nicolas
  • 2,321
  • 4
  • 21
  • 32