메뉴 건너뛰기

Cloudera, BigData, Semantic IoT, Hadoop, NoSQL

Cloudera CDH/CDP 및 Hadoop EcoSystem, Semantic IoT등의 개발/운영 기술을 정리합니다. gooper@gooper.com로 문의 주세요.


Runtime.getRuntime().exe()로 문제가 발생 할만한 상황을 고려하여 만든소스임

String[] args = {"", "", ""};

  // conf값을 확인해서 재설정함
  args[0] = "/home/hadoop/bin/run.sh";
  args[1] = "default"; 
  args[2] = "a.txt";

  StringBuilder sb = new StringBuilder();

  for (String str : args) {
   sb.append(str);
   sb.append(" ");
  }

후에  String[] result = Utils.runShell(sb)을 호출한다. (result[0]은 stdMsg, result[1]은 errorMsg가 넘어온다)

---------------------------------------Utils.java-----------------------------------------------------

(args는 shell명령어및 인자를 넣어서 runShell()을 실행시켜줌)

 public static String[] runShell(StringBuilder args) throws Exception {
  Process process = null;
  boolean notTimeOver = true;
  String[] result = new String[] { "", "" };
  ProcessOutputThread stdMsgT=null;
  ProcessOutputThread errMsgT=null;

  // OS 종류 확인
  String osName = System.getProperty("os.name");

  try {
   String[] cmd = null;
   if (osName.toLowerCase().startsWith("window")) {
    cmd = new String[] { "cmd.exe", "/y", "/c", sb.toString() };
   } else {
    cmd = new String[] { "/bin/sh", "-c", args.toString() };
   }
   // 콘솔 명령 실행
   process = Runtime.getRuntime().exec(cmd);

   // 실행 결과 확인 (에러)
   StringBuffer stdMsg = new StringBuffer();
   // 스레드로 inputStream 버퍼 비우기
   stdMsgT = new ProcessOutputThread(process.getInputStream(), stdMsg);
   stdMsgT.start();

   StringBuffer errMsg = new StringBuffer();
   // 스레드로 errorStream 버퍼 비우기
   errMsgT = new ProcessOutputThread(process.getErrorStream(), errMsg);
   errMsgT.start();

   // 수행종료시까지 대기
   while(true) {
    if(! stdMsgT.isAlive() && ! errMsgT.isAlive()) {
     notTimeOver = process.waitFor(30L, TimeUnit.MINUTES);
     log.debug("Thread stdMsgT Status : "+stdMsgT.getState());
           log.debug("Thread errMsgT Status : "+errMsgT.getState());

     break;
    }
   }
   log.debug("notTimeOver ==========================>" + notTimeOver);

   // 실행결과
   result[0] = stdMsg.toString();
   result[1] = errMsg.toString();
  } catch (Exception e) {
   e.printStackTrace();
   throw e;
  } finally {
   if (process != null) {
    IOUtils.closeQuietly(process.getOutputStream());
    IOUtils.closeQuietly(process.getInputStream());
    IOUtils.closeQuietly(process.getErrorStream());
    
    process.destroy();
    log.debug("process destoryed ==========================>");
   }
  }

  args.delete(0, args.length());
  args.setLength(0);
  args = null;

  return result;
 }

 

--------------------------------ProcessOutputThread .java----------------------------------------------------------

//스레드로 inputStream 버퍼 비우기 위한 클래스 생성
public class ProcessOutputThread extends Thread {
 private InputStream is;
 private StringBuffer msg;

 public ProcessOutputThread(InputStream is, StringBuffer msg) {
  this.is = is;
  this.msg = msg;
 }

 public void run() {
  try {
   msg.append(getStreamString(is));
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (is != null) {
    try {
     is.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 private String getStreamString(InputStream is) {
  BufferedReader reader = null;
  try {
   reader = new BufferedReader(new InputStreamReader(is));
   StringBuffer out = new StringBuffer();
   String stdLine;
   while ((stdLine = reader.readLine()) != null) {
    out.append(stdLine);
   }
   return out.toString();
  } catch (Exception e) {
   e.printStackTrace();
   return "";
  } finally {
   if (reader != null) {
    try {
     reader.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

 

번호 제목 날짜 조회 수
168 null 혹은 ""를 체크하는 방법 2016.01.27 1713
167 sparql 1.1 BIND(if() as ?bind변수) 버그로 추정되는 문제점및 해결방안 -> select 문에 (if(,,) as ?bind변수) file 2016.01.21 1267
166 CDH 5.4.4 버전에서 hive on tez (0.7.0)설치하기 2016.01.14 1578
165 한번에 여러값 update하기 2016.01.13 1537
164 문자열을 숫자(integer)로 casting하기 2016.01.13 2123
163 update(update와 delete->insert)사용시 주의/참고사항 2016.01.06 1783
162 fuseki에 update하는 방법(java api이용)및 주의 사항 2015.12.30 1787
161 mongodb에서 큰데이타 sort시 오류발생에 대한 해결방법 2015.12.22 1857
160 console명령과 API비교 2015.12.21 1888
159 java quartz 시간 설정 참고사항 2015.12.16 1533
158 천문학적, 기후학적, 기상학적, 생물학적, 농사계절 구분 2015.12.16 1528
157 대표 오픈소스 라이선스, 한 눈에 보기! 2015.12.10 1662
156 sparql 문법구조 설명 file 2015.12.09 1909
155 git설명 한글판 2015.12.09 1540
154 protege 4.3 다운로드 2015.12.09 1055
153 ontology, jena, sparql등 전반에 대한 설명및 예제를 제공하는 사이트 2015.12.08 1291
152 마이바티스(MyBatis)쿼리로그 출력및 정렬하기 2015.12.01 2606
151 sparql에서 concat에제 2015.11.27 1491
» Runtime.getRuntime().exec(cmd) sample 소스 2015.11.19 1321
149 Resource temporarily unavailable(자원이 일시적으로 사용 불가능함) 오류조치 2015.11.19 9449
위로