繁体   English   中英

使用简单的Runtime.getRuntime()。exec(cmd)时代码冻结

[英]Code freezing when using simple Runtime.getRuntime().exec(cmd)

当我运行应用程序并扫描IP时,由于某种原因它会冻结。 另外,我不确定Yum方法一旦运行该命令是否会退出,或者它永远存在。 我的目标是制作$ ./inLinuxRunMe &类的东西,使其在后台运行,当工作完成时,它会自行杀死。

我不认为我的Yum方法正在执行此操作,因为当我开始播放视频等重负载时,它会冻结。

public class MyShell
{
    public static String whatIsMyIP = null;

    public static void main(String args[])
    {
      t = new javax.swing.Timer(10000, new ActionListener() 
      {
        public void actionPerformed(ActionEvent ae) 
        {
        /* Scanner: if the ip change, show the new on too. */
        whatIsMyIP = MyShell.Yum("ifconfig eth0 | grep inet").toLowerCase());           
            /* Some logical conditions ... such as if ran then dont run, run once etc..*/ 
            bootMe();
         }
      });
      t.start();

      /* Launch: Main application server, runs forever as server */
      // MyShell.Yum("java -cp myjar.jar launch.MainApplicationAsServer");
    }

    /* Boot loader */
    public static void bootMe() throws IOException
    {
      MyShell.Yum("java -cp myjar.jar launch.MainApplicationAsServer");
    }

    /* Question: How to optimize it? So that, 
             it execute the shell command and quite*/
    public static String Yum(String cmds)
    {
        String value = "";
        try 
        {
          String cmd[] = {"/bin/sh", "-c", cmds };       
          Process p=Runtime.getRuntime().exec(cmd);       
          BufferedReader reader=new BufferedReader(
                                                                            new InputStreamReader(p.getInputStream())); 
          String line=reader.readLine(); 

          while(line!=null) 
          { 
            value += line ;
            line=reader.readLine(); 
          } 
          p.waitFor(); 

        } catch(IOException e1) {
        } catch(InterruptedException e2) { 
        }
        return value;
    }
}

在单独的线程中运行Yum()方法。

通过Java API:

Constructor Summary
Timer(int delay, ActionListener listener)
      Creates a Timer that will notify its listeners every `delay` milliseconds.

因此,它每10秒重复一次。 您需要告诉它不要重复:

public void setRepeats(boolean flag)

    If flag is false, instructs the Timer to send only one action event to its listeners.

    Parameters:
        flag - specify false to make the timer stop after sending its first action event

所以:

t = new javax.swing.Timer(10000, new ActionListener() {...});
t.setRepeats(false);
t.start();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM