簡體   English   中英

如何在java中銷毀一個進程

[英]How to destroy a Process in java

我寫了下面的代碼。 要從Java應用程序運行bat文件,我使用process.exec()。 但是蝙蝠可能會在某個時候掛起,所以我需要為這個過程設置一個超時。 我在線程中啟動一個新線程和一個新進程,我在線程中設置了一個超時,並在超時時終止該線程。 但我發現超時發生時無法銷毀進程。 所以我很擔心如何殺死這條庄園?

代碼:

StreamGobbler:

import java.util.*;

import java.io.*;

class StreamGobbler extends Thread
{
    InputStream is;
    String type;

    StreamGobbler(InputStream is, String type)
    {
        this.is = is;
        this.type = type;
    }

    public void run()
    {
        try
        {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
                System.out.println(type + ">" + line);    
            } catch (IOException ioe)
              {
                ioe.printStackTrace();  
              }
    }
}

主要:

public class test
{

    public static void main(String args[]) throws InterruptedException

    {
        Runnable r = new ShengThread();
        Thread sheng = new Thread(r);
        sheng.start();
        sheng.join(1000);
        if (sheng.isAlive()) {
            sheng.interrupt();
        }

        if (sheng.isAlive()) {
            System.out.println("It is dead.");
        }



    }
}

class ShengThread implements Runnable {

    public void run() {

        Process proc = null;

        try
        {            
            String osName = System.getProperty("os.name" );
            String[] cmd = new String[3];
            if( osName.equals( "Windows XP" ) )
            {
                cmd[0] = "cmd" ;
                cmd[1] = "/C" ;
                cmd[2] = "c:\\status.bat";
            }


            Runtime rt = Runtime.getRuntime();

            System.out.println(osName+"Execing " + cmd[0] + " " + cmd[1] 
                               + " " + cmd[2]);
            try {
                proc = rt.exec(cmd);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // any error message?
            StreamGobbler errorGobbler = new 
                StreamGobbler(proc.getErrorStream(), "ERROR");            

            // any output?
            StreamGobbler outputGobbler = new 
                StreamGobbler(proc.getInputStream(), "OUTPUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();

            // any error???
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);        
        } catch (InterruptedException t)
          {
            System.out.println("start\n");
            proc.destroy();
            t.printStackTrace();
          }

    }
}

Process.destroy()方法強制銷毀外部進程......如果可行的話。 (在某些情況下,你不能破壞進程,但這只是勉強相關。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM