메뉴 건너뛰기

Bigdata, Semantic IoT, Hadoop, NoSQL

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

 

번호 제목 글쓴이 날짜 조회 수
58 magento2 샘플데이타 설치 총관리자 2017.01.31 24
57 [vi] test.nq파일에서 특정문자열(예, <>)을 찾아서 포함되는 라인을 삭제한 동일한 이름의 파일을 만드는 방법 총관리자 2017.01.25 36
56 [u-Auctions]목록이 1개만 나오는 문제 총관리자 2017.05.29 38
55 eclipse 3.1 단축키 정리파일 총관리자 2017.01.02 38
54 magento2 설치후 초기화면이 깨지는 문제 file 총관리자 2017.01.31 42
53 windows 혹은 mac에서 docker설치하기 위한 파일 총관리자 2017.10.13 42
52 magento2 log파일 위치 총관리자 2017.01.31 45
51 webid에서 google처럼 검색할 수 있도록 하는 프로그램 총관리자 2017.05.16 46
50 "암은 평범한 병, 심호흡만 잘해도 암세포 분열 저지” 총관리자 2016.06.02 48
49 LAGOM 1.4 AND KUBERNETES ORCHESTRATION 총관리자 2019.07.19 78
48 에러 추적(Error Tracking) 및 로그 취합(logging aggregation) 시스템인 Sentry 설치 총관리자 2018.03.14 88
47 php auction 프로그램 총관리자 2017.05.14 94
46 컴퓨터 무한 재부팅 원인및 조치방법 file 총관리자 2017.12.05 106
45 https용 인증서 발급 명령문 예시및 오류 메세지 총관리자 2018.01.24 109
44 바나나 파이의 /tmp폴더를 외장하드로 변경하기 총관리자 2015.07.24 136
43 magento2 2.1.3을 수동으로 설치하는 방법 총관리자 2017.02.01 149
42 이미지 관리 오픈소스 목록 총관리자 2018.03.11 149
41 천문학적, 기후학적, 기상학적, 생물학적, 농사계절 구분 총관리자 2015.12.16 150
40 [PHP7.0]로그파일 위치 총관리자 2017.05.07 151
39 대표 오픈소스 라이선스, 한 눈에 보기! 총관리자 2015.12.10 168

A personal place to organize information learned during the development of such Hadoop, Hive, Hbase, Semantic IoT, etc.
We are open to the required minutes. Please send inquiries to gooper@gooper.com.

위로