我使用
            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.
但是没有进一步的说明.只能说明我的子进程被中断了.怎么回事啊?

解决方案 »

  1.   

    java /usr/www/html/java/testdir/test1
    改成
    java -classpath /usr/www/html/java/testdir/ test1
    试试
      

  2.   

    我在window下面试过了:你的代码如果是
    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
      

  3.   

    to:mummy_zc(水煮鱼) 
    谢谢你的提醒,我使用了另外一个exec函数
    exec(cmd.env[])并且设置:
            cmd    = "java test1";
            env[0] = "classpath = /usr/www/html/java/testidir/";
    可以操作成功,问题是我还是看不到程序的输出(到stdout的输出)
      

  4.   

    还有就是我怎么能关闭这个进程,使用process.distory()根本不行.如果得到这个进程的pid,然后调用kill,太复杂了.不知道有没有更好的方法?
      

  5.   

    使用java.lang.reflect包直接调用另外一个class得main方法。
      

  6.   

    我现在勉为其难地让程序执行起来了.虽然不能看到输出.
    现在的问题是:我必须在不和子进程交换数据的基础上杀掉子进程.类似于调用kill.因为我的子进程总是莫名其妙的over了.但是它的进程id还在.让我以为他还活着.实际上这时候他已经不接受我除了kill之外的任何东西了
      

  7.   

    process.distory();
    pocess=null;//别忘了捕捉输出使用
    bufferedR=new BufferedReader(
    new InputStreamReader(test1.getInputStream()));
    String temp=bufferedR.readLine();
    while(temp!=null){
                    System.out.println(temp);
    temp=bufferedR.readLine();
    }
      

  8.   

    process.distory();
    pocess=null;//别忘了
    以后那个进程还是坚停地挂在哪里.我不明白:
    1.为什么做不掉它(因为distory是一个虚函数的原因吗?)
    2.我运行的命令行是java test1.而进程列表里面显示的是:
    /usr/java/j2sdk1.4.0_03/bin/java test1
      

  9.   

    不知道,我没法再linux下去试
      

  10.   

    Process p = null;
        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();
        }
      }