日期:2014-05-20  浏览次数:20592 次

linux下java执行shell命令
我装的是linux8.0,mysql4.0,tomcat5.028,我想在jsp页面中调用shell命令来执行mysql数据库备份的命令。在linux的shell下,测试可以成功。命令如下:
[root@mynet   mysql]#   /usr/local/mysql/bin/mysqldump   -u   root   -p7788919   axtic_cg   >
/usr/xyz.sql
但是在jsp中却不行了。

<%@   page   contentType= "text/html;   charset=gb2312 "   language= "java "   import= "java.sql.* "   %>


<!DOCTYPE   html   PUBLIC   "-//W3C//DTD   XHTML   1.0   Transitional//EN "   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html   xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<meta   http-equiv= "Content-Type "   content= "text/html;   charset=gb2312 "   />
<title> </title>
</head>

<body>
<%
String   commandstr   =   "/usr/local/mysql/bin/mysqldump   -u   root   -p7788919   axtic_cg   >   /usr/xyz.sql ";
Process   p;
try
{
        out.print( "start   backup\n ");
        p   =   Runtime.getRuntime().exec(commandstr);
        if   (p.waitFor()   ==   0)
        {
out.print( "backup   over\n ");

        }
        else
        {
out.print( "backup   fail\n ");

        }
}
catch   (Exception   e)
{
        out.print( "backup   fail\n ");
        out.println(e.toString());
}
%>
</body>
</html>
可是我把命令改成了String   commandstr   =   "who   am   i "
却又显示的是backup   over.

------解决方案--------------------
原因是java runtime.process run的一个bug

网上有很多解决方案

只有把outputstream /error stream即使的清空,命令才能完成,否则会一直等待

而且linux/solaris下面默认的shell buffer很小,很容易出现这种情况
------解决方案--------------------
去google搜索一下 ExecRunner pitfall

http://www.koders.com/java/fidE74E642685BBC1DC815063846EAB0BC63566E554.aspx
------解决方案--------------------
学到东西了。。。