In ruby…
I have an IO object created by an external process, which I need to get the file name from.
However I only seem to be able to get the File descriptor (3), which is not very useful to me.
Is there a way to get the filename from this object or even to get a File Object?
I am getting the IO object from notifier. So this may be a way of getting the file path as well?
There is a similar question on how to get a the filename in C, I will present here the answer to this question in a ruby way.
Getting the filename in Linux
Suppose
iois your IO Object. The following code gives you the filename.This does not work for example if the file was removed after the io object was created for it. With this solution you have the filename, but not an File object.
Getting a File object which does not know the filename
The method
IO#for_fdcan create an IO and it’s subclasses for any given integer filedescriptor. Your get your File object for your fd by doing:Unfortunely this File object does not know the filename.
I scanned through the ruby-1.9.2 sources. There seems to be no way in pure ruby to manipulate the path after the file object was created.
Getting a File object which does know the filename
An extension to ruby can be created in C which first calls
File#for_fdand afterwards manipulates the Files internal data structures. This sourcecode does work for ruby-1.9.2, for other versions of ruby it may has to be adjustet.Now you can do after compiling:
The readlink could also be put into the
File#for_fd_with_filenamedefiniton. This examples is just to show how it works.