메뉴 건너뛰기

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

 

번호 제목 날짜 조회 수
59 Resource temporarily unavailable(자원이 일시적으로 사용 불가능함) 오류조치 2015.11.19 11597
58 mysql 5.5.34-0ubuntu0.13.04용 설치/진행 화면 2014.09.10 9947
57 Ubuntu 16.04LTS 설치후 초기에 주어야 하는 작업(php, apache, mariadb설치및 OS보안설정등) file 2017.05.23 7828
56 원보드pc인 bananapi를 이용하여 hadoop 클러스터 구성하기(준비물) file 2014.05.29 6431
55 checking for termcap functions library... configure: error: No curses/termcap library found 2013.03.08 6097
54 빅데이터 분석을 위한 샘플 빅데이터 파일 다운로드 사이트 2014.04.28 5336
53 의사분산모드에 hadoop설치및 ecosystem 환경 정리 2014.05.29 5170
52 https용 인증서 발급 명령문 예시및 오류 메세지 2018.01.24 4633
51 ../depcomp: line 512 exec : g++ : not found 2013.03.08 4527
50 How to Install Magento 2.4.7 on Ubuntu 24.04 2024.09.04 4504
49 apt-get install mysql-server수행시 "404 Not Found" 오류발생시 조치방법 2014.09.10 4462
48 ubuntu에 hadoop 2.0.5설치하기 2013.12.16 4459
47 통계자료 구할수 있는 곳 2014.04.16 4361
46 [Magento]php7에 Composer를 이용하여 Magento 2.1.3 설치 file 2017.01.30 4348
45 MySQL 다운로드 및 리눅스에서 간단 컴파일 설치 2013.03.08 4309
44 우분투 16.04 LTS에 apache2와 tomcat7 연동하여 설치하기 2014.05.09 4309
43 시스템날짜를 현재 정보로 동기화 하는 방법(rdate, ntpdate이용) 2014.08.24 4297
42 원격지에서 zio공유기를 통해서 노트북의 mysql접속을 허용하는 방법 2014.09.07 4278
41 로그 파일에 대해 Elasticsearch 사용하기 2014.09.25 4260
40 RHadoop을 통해서 웹사이트의 방문자수를 예측하는 방법 2014.09.26 4258
위로