Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a numbered file descriptor from Java

I need to access numbered file descriptors from Java -- other than 0, 1 or 2.

How can this be done? I looked at the FileDescriptor class but did'nt find any way to initialize it with a given file descriptor number.

As a concrete example lets suppose Java gets called as a child process from another programing language. File descriptors 3 and 4 are provided by the other language for input and output.

What I need in Java are InputStream and OutputStream objects connected to these file-descriptors, just like System.in, System.out and System.error are connected to file-desctiptors 0, 1 and 2.

I'm using Java 1.6 and this should run on Unix alike systems.

like image 680
Peer Stritzinger Avatar asked Jan 30 '11 19:01

Peer Stritzinger


People also ask

How do I find file descriptor number?

Use the ulimit -n command to view the number of file descriptors configured for your Linux system.

What is a file descriptor in Java?

Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes. The main practical use for a file descriptor is to create a FileInputStream or FileOutputStream to contain it.

What is a file descriptor number?

A file descriptor is a number that uniquely identifies an open file in a computer's operating system. It describes a data resource, and how that resource may be accessed. When a program asks to open a file — or another data resource, like a network socket — the kernel: Grants access.

How do I print a file descriptor?

You don't print a FILE* descriptor, it's a pointer to opaque data that is totally implementation dependent. Under Linux, You need to print the individual members of the file descriptor. For e.g. you have a file pointer FILE *fp to print the _flag use fp->_flag .


2 Answers

I'm pretty sure this can't be done using pure Java -- you'll probably have to use native code to bind a file descriptor to a FileDescriptor object or a FileInputStream or FileOutputStream object.

EDIT
If you're using Linux, *BSD or macOS, you can use the pseudo files /dev/fd/nnn to access file-descriptor nnn.

like image 97
Adrian Pronk Avatar answered Oct 05 '22 11:10

Adrian Pronk


With a SUN JavaVM you can do:

FileDescriptor fd = new FileDescriptor();
sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess().set(fd,3);
FileInputStream fin = new FileInputStream(fd);
like image 38
paf.goncalves Avatar answered Oct 05 '22 13:10

paf.goncalves