SSISO Community

시소당

Process 관리하기

java  프로그램  내부에서  특정  프로그램을  실행시킨다던지  강제로  죽일  필요가  있을때가  있다.
그리고  몇개의  프로그램을  관리하는  관리프로그램을  만들때도  필요할것이다.    
프로그램을  실행시킨  부모  프로그램은  자식프로그램으로  부터  에러메시지나  기타메시지들을  받고  
관리할수도  있다.  

기본적인  클래스
Runtime
Every  Java  application  has  a  single  instance  of  class  Runtime  that  allows  the  application  to  interface  
with  the  environment  in  which  the  application  is  running.  The  current  runtime  can  be  obtained  from  the  getRuntime  
method.  
getRuntime  메소드로  현재  Runtime  객체의  참조를  가져올수  있으며  이것으로  프로세스객체를  접근하기
위한  참조를  가져올수  있다.  

Process
The  ProcessBuilder.start()  and  Runtime.exec  methods  create  a  native  process  and  return  an  instance  of  
a  subclass  of  Process  that  can  be  used  to  control  the  process  and  obtain  information  about  it.  The  class  Process  
provides  methods  for  performing  input  from  the  process,  performing  output  to  the  process,  waiting  for  the  process  to  
complete,  checking  the  exit  status  of  the  process,  and  destroying  (killing)  the  process.  
Runtime  객체를  통해  가져온  특정  프로세스를  관리하는  기능을  하는데  프로세스로  부터의  input,  output  
스트림을  제어할수있다.

Runtime  rt  =  Runtime.getRuntime();      
long  time  =  System.currentTimeMillis();
try  {      
        /**  표준입출력  */
        Process  proc  =  rt.exec("gogo.exe")
        InputStream  is  =  proc.getInputStream();      
        BufferedReader  reader  =  new  BufferedReader(new  InputStreamReader(is));      
        String  line;      
        while  ((line  =  reader.readLine())  !=  null)  {      
                System.out.println(line);      
        }
        /**  에러입출력  */
        InputStream  standardError  =  process.getErrorStream();  //  에러스트림을  가져온다.
        InputStreamReader  ow  =  new  InputStreamReader(standardError);  //  에러스트림을  읽어들인다
        BufferedReader  errorReader  =  new  BufferedReader(ow);//  버퍼로  읽어들인다.
        StringBuffer  stderr  =  new  StringBuffer();
        String  lineErr  =  null;
        while((lineErr  =  errorReader.readLine())  !=  null){
                stderr.append(lineErr).append("\n");
        }
        //  에러데이타를  콘솔에  출력
        System.out.println(stderr.toString());

        int  exitVal  =  proc.waitFor();      
        System.out.println("Process  exited  with  "  +  exitVal);      

}  catch  (IOException  e)  {
            e.printStackTrace();
}  catch  (Exception  e)  {      
          System.err.println("Failed  to  execute:  "  +  e.getMessage());      
}    finall{
        if  (process  !=  null)
                process.destory();
        System.out.println("경과시간    "  +  (System.currentTimeMillis()  -  time)  +  "ms");
}

예제에서  보는것과  같이  프로그램명을  인자로  전달하게  되면  실행하고  그  프로세스  참조를  리턴하게된다.
그리고  프로세스가  표준입출력이  필요할때는  블럭이  되지  않도록  비워줘야한다.
Process.getOutputStream()을  이용하여  필요한  입력을  해주고  스트림을  닫아주어야하고,  표준  출력이  필요할  때는  Process.getInputStream()  그리고  Process.getErrorStream()을  이용하여  스트림을  비워주어야한다.  
참고로  자바에서는  네트웍데이타나  프로세스간전송데이타등은  읽는  방식이  동일하다.
(1)  InputStream    레퍼런스를  리턴받아서  ->  (2)  InputStreamReader  객체로  읽어들인다  ->  
(3)  읽어들인  바이트  데이타를  Line  별로  쉽게  출력할수  있도록  BufferedReader  객체로  읽어들이다.

출처  :  http://mainia.tistory.com/entry/Process-관리하기

[2009년  01월  06일  20:34:54  수정되었습니다.]

1866 view

4.0 stars