【问题标题】:Java executing commands in Operating SystemJava在操作系统中执行命令
【发布时间】:2009-10-14 14:05:13
【问题描述】:

我有一个在操作系统中执行特定命令的 Java 程序。我还使用 Process.waitfor() 如下代码所示来指示执行是成功完成还是失败。

我的问题是,有没有其他方法可以避免使用 process.waitfor(),有没有办法使用 while 循环并执行某些操作,直到进程完成?

            Runtime rt = Runtime.getRuntime();

        Process p = rt.exec(cmdFull);

        BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String inStreamLine = null;
        String inStreamLinebyLine=null;
        while((inStreamLine = inStream.readLine()) == null) {
          inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine;
        }


        try {
            rc = p.waitFor();

        } catch (InterruptedException intexc) {
            System.out.println("Interrupted Exception on waitFor: " +
                               intexc.getMessage());
        }    

我想做的事情是这样的

            Runtime rt = Runtime.getRuntime();

        Process p = rt.exec(cmdFull);

        BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String inStreamLine = null;
        String inStreamLinebyLine=null;
        while((inStreamLine = inStream.readLine()) == null) {
          inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine;
        }


        try {

            while ((rc = p.waitFor()) == true ) { // This is made up, I don't even think it would work
                System.out.println('Process is going on...');
            }


        } catch (InterruptedException intexc) {
            System.out.println("Interrupted Exception on waitFor: " +
                               intexc.getMessage());
        }    

谢谢,

【问题讨论】:

    标签: java


    【解决方案1】:

    也许这样的事情会奏效。按照@tschaible 的建议创建一个线程,然后在该线程上执行一个超时连接(这是您在代码中编写的部分)。它看起来像这样:

    Thread t = new Thread(new Runnable() { 
    
      public void run() {
        // stuff your code here
      }
    
    });
    t.run();
    
    while (t.isAlive()) {
      t.join(1000); // wait for one second
      System.out.println("still waiting");
    }
    

    它的作用是将代码作为一个单独的线程启动,然后测试胎面是否每隔一秒完成一次。当线程完成并且不再活动时,while 循环应该结束。您可能需要检查 InterruptedException,但我现在无法测试。

    希望这会让你朝着正确的方向前进。

    【讨论】:

      【解决方案2】:

      您可以在开始进程之前生成一个新线程。

      新线程将负责打印出“进程正在进行...”或任何需要的内容。

      p.waitFor() 完成后,启动进程的主线程将向新线程指示它应该停止运行。

      【讨论】:

        【解决方案3】:

        您可以生成一个新的thread 并在线程中等待,通过共享变量从主线程定期检查等待线程是否已完成。

        【讨论】:

          猜你喜欢
          • 2019-05-13
          • 1970-01-01
          • 2015-09-14
          • 1970-01-01
          • 2014-03-03
          • 2013-02-01
          • 2013-10-21
          • 2016-11-28
          • 2020-09-25
          相关资源
          最近更新 更多