메뉴 건너뛰기

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();
    }
   }
  }
 }
}

 

번호 제목 날짜 조회 수
290 시스템날짜를 현재 정보로 동기화 하는 방법(rdate, ntpdate이용) 2014.08.24 4297
289 [Ranger]계정에 admin권한(grant, create등)의 권한 부여 방법 2023.04.18 4298
288 Scala를 이용한 Streaming예제 2018.03.08 4299
287 MySQL 다운로드 및 리눅스에서 간단 컴파일 설치 2013.03.08 4310
286 hue.axes_accessattempt테이블 데이터 샘플 2020.02.10 4313
285 우분투 16.04 LTS에 apache2와 tomcat7 연동하여 설치하기 2014.05.09 4315
284 apk 파일 위치 file 2015.05.25 4321
283 Soft memory limit exceeded (at 100.05% of capacity) 오류 조치 2022.01.17 4322
282 conda를 이용한 jupyterhub(v0.9)및 jupyter설치 (v4.4.0) 2018.07.30 4323
281 mybatis와 spring을 org.apache.commons.dbcp2.BasicDataSource의 DataSource로 연동할때 DB설정(참고) 2016.10.31 4324
280 sqoop으로 mariadb에 접근해서 hive 테이블로 자동으로 생성하기 2018.08.03 4324
279 [KTS Cluster의 Key Trustee Server]self-signed 인증서 발급및 설정 방법 2023.06.27 4324
278 로컬에 있는 jar파일을 지정하고 dependency로 가져오기 2016.08.19 4325
277 jsoup 사용 예제 2014.06.06 4333
276 os가 windows7인 host pc에서 ubuntu가 os인 guest pc에 접근하기 위한 네트워크설정 2014.04.20 4336
275 Impala의 Queries탭에서 여러조건으로 쿼리 찾기 2018.05.09 4337
274 [Impala TLS/SSL이슈]RangerAdminRESTClient.java:151] Failed to get response, Error is: TrustManager is not specified 2023.02.02 4339
273 Flume과 Kafka를 사용한 초당 100만개 로그 수집 테스트 file 2016.10.31 4340
272 커리 변경 이벤트를 처리하기 위한 구현클래스 2016.07.21 4344
271 Cassandra 3.4(3.10) 설치/설정 (5대로 clustering) 2016.04.11 4345
위로