I recently needed to do this for a Java child process running in a jail. This meant it did not have access to the /dev/fd filesystem.
@Bozho made a comment that reflection may or may not work to create a FileDescriptor object. It appears to work in a simple test I did, though. The following is source for TestFD.java:
import java.lang.reflect.Constructor;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
public class TestFD {
public static void main(String[] args) throws Exception {
Constructor<FileDescriptor> ctor = FileDescriptor.class.getDeclaredConstructor(Integer.TYPE);
ctor.setAccessible(true);
FileDescriptor fd = ctor.newInstance(3);
ctor.setAccessible(false);
new FileOutputStream(fd).write("hi there\n".getBytes());
}
}
To test this, I made a simple Bash script that compiles it, sets up fd3, and runs the java program:
#!/bin/bash
javac TestFD.java
exec 3>&1 # open fd3, redirect to stdout
java TestFD
exec 3>&-
Sure enough, fd3 is redirected to stdout, and outputs "hi there\n" on the terminal. Comment out the "exec 3>&1" line and the Java program fails as expected with a "Device not configured" IOException.
Reflection on the private FileDescriptor constructor seems to work fine in cases where access to /dev/fd is not possible, and is less clunky than trying to create a FileDescriptor using JNI, a suggestion that I have seen elsewhere.
Note: I tested this on a BSD system. It may or may not work on other systems.