Skip to content

Instantly share code, notes, and snippets.

@wware
Last active August 13, 2018 23:25
Show Gist options
  • Save wware/93f14849f22a3a565e7328b0fa7a3975 to your computer and use it in GitHub Desktop.
Save wware/93f14849f22a3a565e7328b0fa7a3975 to your computer and use it in GitHub Desktop.

Non-blocking

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment