簡體   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