001    /*
002     * To change this template, choose Tools | Templates
003     * and open the template in the editor.
004     */
005    package org.bridj.util;
006    
007    import org.bridj.ann.Library;
008    import java.io.File;
009    import java.io.IOException;
010    import java.util.ArrayList;
011    import java.util.List;
012    
013    import org.bridj.BridJ;
014    import org.bridj.Platform;
015    import org.bridj.ann.Convention;
016    import static java.lang.System.getProperty;
017    
018    /**
019     * Util methods to : query the process id from the current process, launch processes (including JVM processes)
020     * @author Olivier
021     */
022    public class ProcessUtils {
023    
024        @Library("kernel32")
025        @Convention(Convention.Style.StdCall)
026        static class Kernel32 {
027            public static native int GetCurrentProcessId();
028        }
029        @Library("c")
030        static class LibC {
031            public static native int getpid();
032        }
033        
034        /**
035         * Get the current process native id
036         */
037        public static int getCurrentProcessId() {
038            if (Platform.isWindows()) {
039                BridJ.register(Kernel32.class);
040                return Kernel32.GetCurrentProcessId();
041            } else {
042                BridJ.register(LibC.class);
043                return LibC.getpid();
044            }
045        }
046        
047        public static String[] computeJavaProcessArgs(Class<?> mainClass, List<?> mainArgs) {
048            List<String> args = new ArrayList<String>();
049            args.add(new File(new File(getProperty("java.home")), "bin" + File.separator + "java").toString());
050            args.add("-cp");
051            args.add(getProperty("java.class.path"));
052            args.add(mainClass.getName());
053            for (Object arg : mainArgs)
054                args.add(arg.toString());
055            
056            return args.toArray(new String[args.size()]);
057        }
058        public static Process startJavaProcess(Class<?> mainClass, List<?> mainArgs) throws IOException {
059            ProcessBuilder b = new ProcessBuilder();
060            b.command(computeJavaProcessArgs(mainClass, mainArgs));
061            b.redirectErrorStream(true);
062            return b.start();
063        }
064        
065    }