본문 바로가기

카테고리 없음

android에서 리눅스 명령어 실행

728x90

http://sailerya.tistory.com/6

        Runtime runtime = Runtime.getRuntime(); 
        Process process; 
        String res = "-0-"; 
        try { 
                String cmd = "top -n 1"; 
                process = runtime.exec(cmd); 
                BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); 
                String line ; 
                while ((line = br.readLine()) != null) { 
                 Log.i("test",line);
                } 
        } catch (Exception e) { 
                e.fillInStackTrace(); 
                Log.e("Process Manager", "Unable to execute top command"); 
        }



http://blog.burt.pe.kr/


안드로이드에서 명령문 실행하기

Java의 표준 라이브러리인 Runtime  을 이용해서 실행할 수 있다. Runtime.exec() 를 통해서 Process 를 생성하고 Process 가 stdout에서 Process가 뱉는 결과를 받아 오는 방식이다. 아래의 예제는 ls 명령어를 실행하는 예제이다.

실행결과

실행결과


Process prc=Runtime.getRuntime().exec("ps | grep applicationname");

//applicationname으로 process에서 찾기 시작.

BufferedReader  rdr = new BufferedReader(new InputStreamReader(prc.getInputStream()));

char[] buffer = new char[1024];

//buffer의 길이를 1024


rdr.read(buffer);

//rdr 객체에서 buffer 만큼 읽기

StringBuffer output = new StringBuffer();

output.append(buffer, 0, 1024);

//buffer의 를 output stringbuffer에 옮기기

resString=output.toString();

//output 스트링을 resString 이라는 String 객체에 복사


String[] test=resString.split("\\s+");

//resString 객체를 띄어쓰기 마다 잘라서 test 스트링 배열에 저장

prc=Runtime.getRuntime().exec("cat /proc/"+test[9]+"/maps");

// test[9]에는 해당 application의 pid가 저장되어 있다. 이를 이용해 maps 정보를 가져올 수 있다.  (이를 가져오기 위해선 root 권한이 필요. 따라서 일반적인 상황에선 permission error남)



참고 : 위의 조잡한 string 객체 생성을 피하고 단순하게도 할 수 있음.






mㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

public class CurlConnect {

public static void RunCurl(String input) throws RuntimeException {

try {


Process prc = Runtime.getRuntime().exec("ps | grep live");

/*

"curl '" + "http://dic.naver.com/search.nhn?dicQuery="

+ input + "&query=" + input

+ "&target=dic&ie=utf8&query_utf=&isOnlyViewEE="

+ "'");

*/

BufferedReader rdr = new BufferedReader(new InputStreamReader(

prc.getInputStream()));

char[] buffer = new char[1024];

// buffer의 길이를 1024


rdr.read(buffer);

// rdr 객체에서 buffer 만큼 읽기

StringBuffer outBuff = new StringBuffer();

outBuff.append(buffer, 0, 1024);

TransService.output=outBuff.toString();//rdr.readLine(buffer).toString();//

//TransService.output=outBuff.toString();

//TransService.output="hello";

// buffer의 를 output stringbuffer에 옮기기

//return TransService.output;

} catch (IOException e) {

throw new RuntimeException(e);


//return null;

}

}