我使用
i = test2.waitFor();
System.out.println("返回值" + i);
立即得到了(而我的test1至少要运行半分钟):
返回值:127
而sun的文档说:This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.
但是没有进一步的说明.只能说明我的子进程被中断了.怎么回事啊?
i = test2.waitFor();
System.out.println("返回值" + i);
立即得到了(而我的test1至少要运行半分钟):
返回值:127
而sun的文档说:This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.
但是没有进一步的说明.只能说明我的子进程被中断了.怎么回事啊?
改成
java -classpath /usr/www/html/java/testdir/ test1
试试
cmd[0] = "/bin/sh";
cmd[1] = "java /usr/www/html/java/testdir/test1";
try{
Process test1 = Runtime.getRuntime().exec(cmd);
}catch(Exception e)
{
System.out.println("create process test1 failed:" + e.getMessage());
}
是不会运行的,虽然没有爆出异常。
再加上一个参数
//第三个参数指明了你的工作目录,你想通过>output.txt,我也没实现,我感觉那决不是加在第一各参数里面,应该是第二个参数里面,专门设置环境变量,就是标准输出定向。这个估计很麻烦。
Process test1 = Runtime.getRuntime().exec(cmd,null,new File("/yourPath"));
但是上面这行保证能够运行。(我通过生成文件测试)如果我是你我会选择使用动态运行java程序,用com.tools.javac包里面的类,推荐你看一篇文章:
http://it.sohu.com/32/37/article208683732.shtml
谢谢你的提醒,我使用了另外一个exec函数
exec(cmd.env[])并且设置:
cmd = "java test1";
env[0] = "classpath = /usr/www/html/java/testidir/";
可以操作成功,问题是我还是看不到程序的输出(到stdout的输出)
现在的问题是:我必须在不和子进程交换数据的基础上杀掉子进程.类似于调用kill.因为我的子进程总是莫名其妙的over了.但是它的进程id还在.让我以为他还活着.实际上这时候他已经不接受我除了kill之外的任何东西了
pocess=null;//别忘了捕捉输出使用
bufferedR=new BufferedReader(
new InputStreamReader(test1.getInputStream()));
String temp=bufferedR.readLine();
while(temp!=null){
System.out.println(temp);
temp=bufferedR.readLine();
}
pocess=null;//别忘了
以后那个进程还是坚停地挂在哪里.我不明白:
1.为什么做不掉它(因为distory是一个虚函数的原因吗?)
2.我运行的命令行是java test1.而进程列表里面显示的是:
/usr/java/j2sdk1.4.0_03/bin/java test1
Properties envVars = new Properties();
Runtime r = Runtime.getRuntime();
try
{
p = r.exec( "cmd.exe /c chkdsk" );
BufferedReader br = new BufferedReader ( new InputStreamReader( p.getInputStream() ) );
String line;
while( (line = br.readLine()) != null ) {
System.out.println(line);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}