Created
June 6, 2021 01:30
-
-
Save yskszk63/2256f1017c18aa7c310127df062bf8b8 to your computer and use it in GitHub Desktop.
forking Java process with panama-foreign
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.invoke.MethodType; | |
import jdk.incubator.foreign.CLinker; | |
import jdk.incubator.foreign.FunctionDescriptor; | |
import jdk.incubator.foreign.LibraryLookup; | |
import jdk.incubator.foreign.MemoryAddress; | |
// run with `java --add-modules jdk.incubator.foreign -Dforeign.restricted=permit Main.java` | |
// | |
// TODO | |
// - Sometimes the child process hangs | |
public class Main { | |
public static void main(String...args) throws Throwable { | |
var lookup = LibraryLookup.ofDefault(); | |
var linker = CLinker.getInstance(); | |
var fork = linker.downcallHandle( | |
lookup.lookup("fork").get(), | |
MethodType.methodType(int.class), | |
FunctionDescriptor.of(CLinker.C_INT)); | |
var waitpid = linker.downcallHandle( | |
lookup.lookup("waitpid").get(), | |
MethodType.methodType(int.class, int.class, MemoryAddress.class, int.class), | |
FunctionDescriptor.of(CLinker.C_INT, CLinker.C_INT, CLinker.C_POINTER, CLinker.C_INT)); | |
var _exit = linker.downcallHandle( | |
lookup.lookup("_exit").get(), | |
MethodType.methodType(void.class, int.class), | |
FunctionDescriptor.ofVoid(CLinker.C_INT)); | |
System.out.println("forking.."); | |
var child = (int) fork.invokeExact(); | |
System.out.println("forked."); | |
if (child == 0) { | |
System.out.println("I am child"); | |
_exit.invokeExact(0); | |
} else if (child < 0) { | |
throw new Exception("failed to fork"); | |
} else { | |
System.out.println("I am parent"); | |
@SuppressWarnings("unused") | |
var r = (int) waitpid.invokeExact(child, MemoryAddress.NULL, 0); | |
} | |
} | |
} |
$ pgrep java
7772
7802
$ ls /tmp/hsperfdata_*
7772
$
Maybe java isn't designed to fork?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ok
ng