2012-03-12 50 views
1

我想使用Process.waitFor()等到mysqldump完成其备份过程。这是我的代码。Process.waitFor()在mysql备份期间永远等待

///i use this mysql command, its working fine 
    String dump = "bkprefs/mysqldump " 
      + "--host=localhost "  
      + "--port=3306 " 
      + "--user=root " 
      + "--password= " 
      + "--add-drop-table " 
      + "--add-drop-database " 
      + "--complete-insert " 
      + "--extended-insert " 
      + "test"; 
    //execute the command 
    Process run = null; 
    try { 
     run = Runtime.getRuntime().exec(dump); 
     int stat = run.waitFor(); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 

问题是,run.waitfor()挂起。它似乎一直在等待一些不会发生的事情。

当我将行int stat = run.waitFor()替换为Thread.sleep(5)时,备份工作正常。但我不能坚持这一点,因为备份时间会根据数据库的大小而有所不同,因此使用Thread.sleep等待备份过程完成并不安全。

请帮帮我。回复非常感谢。

编辑:

我使用下面的代码消耗其输入流。

InputStream in = run.getInputStream(); 
    FileWriter fstream = null; 
    try { 
     fstream = new FileWriter("haha.sql"); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
    BufferedWriter out = new BufferedWriter(fstream); 

    int nextChar; 
    StringBuffer sb = new StringBuffer(); 
    try { 
     while ((nextChar = in.read()) != -1) { 
      out.write((char) nextChar); 
      //sb.append((char) nextChar); 
     } 
     out.flush(); 
     out.close(); 

    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 

回答

2

您需要消耗来自子流程的输出流。这article详细介绍了成功使用过程所需的一切。 (另外,这可能已经在stackoverflow中被回答了很多次)。

+0

我刚刚发布的代码后面的代码完全符合您的说法 – Jemp 2012-03-12 14:57:59

+0

@Bnrdo - 您是否在使用_separate Thread_来处理这些流(详见该文章)? – jtahlborn 2012-03-12 17:25:00

+0

不,用于处理这些流的代码实际上遵循备份代码。 – Jemp 2012-03-13 13:12:12

1

mysqldump转储到标准输出。您可能需要阅读该流,或使用选项-r重定向输出。

+0

谢谢你的回复。我编辑了我的帖子,所以你看到我读了流,所以我认为这不是我的问题。 – Jemp 2012-03-12 15:02:44