Sunday, January 30, 2011

Using a numbered file descriptor from Java

Programmer Question

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.



Tested working solution:



The answer with the file descriptor special filesystem entries did point me to the following workable solution:




  1. find out if and where your Unix alike system has a special filesystem that contains named entries for all file descriptors.




    • I'm using FreeBSD where fdescfs(5) is a filesystem that does just this. Under Linux it would be procfs.


  2. make sure this filesystem is mounted




    • FreeBSD: put fdescfs /dev/fd fdescfs rw 0 0 in /etc/fstab



      or run mount -t fdescfs null /dev/fd on a shell prompt (probably with sudo)



  3. Use new FileInputStream("/dev/fd/3") and new FileOutputStream("/dev/fd/4") to get the streams connected to the filedescriptors (the paths are for FreeBSD, replace with your operating systems paths)




Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails