The System.lang.Runtime.exec() method is non-blocking, so you call it and it spawns a background process.
Unfortunately the java.lang.Process thingy in Java 8 has no way to get a PID, so you need a cheesy hack to find it.
| /* javac Main.java && CLASSPATH=. java Main */ | |
| import java.lang.Runtime; | |
| import java.lang.Process; | |
| import java.io.InputStreamReader; | |
| import java.io.BufferedReader; | |
| public class Main { | |
| public static void main(String[] args) throws Exception { | |
| System.out.println("Here we go"); | |
| String commandLine = "./yoyoyo.sh"; | |
| Runtime.getRuntime().exec(commandLine); | |
| Process proc = Runtime.getRuntime().exec("ps aux"); | |
| BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); | |
| int pid = -1; | |
| String line = null; | |
| while ((line = br.readLine()) != null) { | |
| String cmd = line.substring(65); | |
| if (commandLine.equals(cmd) || ("/bin/sh " + commandLine).equals(cmd)) { | |
| String[] fields = line.split(" +"); | |
| pid = Integer.parseInt(fields[1]); | |
| break; | |
| } | |
| } | |
| System.out.println(pid); | |
| } | |
| } |
| #!/bin/sh | |
| sleep 5 | |
| touch yoyoyo.txt |