[tech][Java]Unixç³»Javaã§Runtime.execãã¤ããã¨ãã®è½ã¨ãç©´
Javaã§ã¯JVMãã©ã¤ãã©ãªã®å®è£
ãWindowsãMacOSãLinuxçã§å
±éã®å®è£
ã ããæ¡ç¨ããæ¹éã ã£ãããã¾ãã
ãªã®ã§ãã·ã³ããªãã¯ãªã³ã¯ãã¯ã£ããã¨ãã£ããããªã使ããããªããããªæ°ã®å©ããOSã®æ©è½ã¯APIã§ã¯ç¨æããã¦ãã¾ããããããããªãã®ã§ãlnã³ãã³ãã¨ãã£ããããªå¤é¨ã³ãã³ããå¼ã³åºãããæ°åã«ãªãã®ã§ãããUnixç³»Javaã§Runtime.exec()ã使ã£ã¦å¤é¨ã³ãã³ããå¼ã³åºãéã«ã¯æ³¨æãå¿
è¦ã§ããæå¤ãªè½ã¨ãç©´ãå¾
ã£ã¦ãã¾ãã
ããä»ãµã¼ãã¼ãUnixç³»OSã§Javaã§Runtime.exec()ã使ããã¨æã£ã¦ãããªããä»ããå¥ã®æ¹æ³ãæ¤è¨ãã¦ãã ãããå¾ã§ã¨ãã§ããªãç®ã«ããã¾ããã
ãã£ããã©ããããã¨ãªãã§ããããï¼ã¨ããããããããªããã°ã©ã ãèãã¦ã¿ã¾ãã
package org.kazumi007; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class ExecuteCommand { public static void main(String[] args) { // 400Mbyteç¢ºä¿ int[] list = new int[2000000]; list[0] = 1; String cmd = "sleep 1"; while (true) { try { Process process = Runtime.getRuntime().exec(cmd); InputStream is = process.getInputStream(); BufferedReader br = new BufferedReader( new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { // ãªã«ãããªã } } catch (IOException e) { e.printStackTrace(); } } } }
å 容ã¯åç´ã§ãã巨大ãªé åã確ä¿ãã¦sleepã³ãã³ãã1ç§ããã«èµ·åãã¦ããã ãã®åç´ãªããã°ã©ã ã§ããããã®ã©ããåé¡ãªã®ã§ããããï¼
å®è¡ä¸ã®Javaããã»ã¹ã®ã¡ã¢ãªãã¿ã¦ã¿ã¾ãããã»ã»ã»ãä½åº¦ãåå¾ããçµæã®ä¸é¨ã§ãã
$ ps -a -o vsz,comm,args,pid,ppid |grep java
75732 grep grep java 22292 20554
1300640 /usr/bin/java /usr/bin/java -Xmx512m org.kazumi007.ExecuteCommand 22086 10150
1300640 /usr/bin/java /usr/bin/java -Xmx512m org.kazumi007.ExecuteCommand 22290 22086
OSX 10.6.1ã®java version "1.6.0_15"ã§ãã¹ããã¾ããã
åãã¡ã¢ãªãµã¤ãºã®Javaã®ããã»ã¹ã2ã¤ããã¾ããããªã«ããï¼ï¼
å®ã¯Unixç³»ã®JVMã¯Runtime.execãå®è¡ãããã¨ãå é¨ã§fork()ãå¼ã³åºãããã»ã¹ã®ã³ãã¼ãä½æããexec()ã§ã³ãã³ããå®è¡ãã¦ããã®ã§ãããã®å®è£ ã®ããã«ãã³ãã³ããçæããã¨å¿ ãèµ·åå ã®ããã»ã¹ã¨åããµã¤ãºã®ç©ºãã¡ã¢ãªããªããã°ãªãã¾ãããããã«èªä½ãæªãããã®ããWindowsã§ã¯å®è£ ãç°ãªãã®ã§é常éçºç°å¢ã§ã¯åé¡ã«ãªããªãã®ã§ããæ¬çªã§ã¯OutOfMemoryErrorãåºããã ãã©ãåç¾ããªãã»ã»ã»ãã¨ãããã¨ã«ãªã£ã¦ãã¾ãã®ã§ãã
大åãªãã¨ãªã®ã§ãããä¸åº¦æ¸ãã¾ãã
Unixç³»Javaã§Runtime.execã使ããªããèµ·åå ã®ããã»ã¹ã§ä½¿ç¨ãã¦ããã¡ã¢ãªã¨åéã®ç©ºã容éãå¿ è¦ã§ããå¯è½ãªéããJavaããå¤é¨ã³ãã³ããå¼ã³åºããã«å¥ã®æ¹æ³ãæ¤è¨ãã¾ãããã
ããã£ã¦Javaã§éçºããã¨ãã®å¸¸èãªãã§ããï¼