Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fopen and getting system file descriptor

I want to get a system file descriptor of the returned resource when I open a file using open. I assume the descriptor is an INT value which is normally inside /dev/fd/

I know that I can read from the descriptor by doing something like:

fread("php://fd/$descriptor", $buflen);

But now I want to get the descriptor for a resource opened by PHP's fopen(). Is there a way?

like image 549
Subrat Basnet Avatar asked Apr 08 '11 21:04

Subrat Basnet


People also ask

Does fopen return a file descriptor?

The open function is the underlying primitive for the fopen and freopen functions, that create streams. Preliminary: | MT-Safe | AS-Safe | AC-Safe fd | See POSIX Safety Concepts. This function is similar to open . It returns a file descriptor which can be used to access the file named by filename .

What are the 3 standard file descriptors?

Stdin, stdout, and stderr On a Unix-like operating system, the first three file descriptors, by default, are STDIN (standard input), STDOUT (standard output), and STDERR (standard error).

What are file descriptors and how are they assigned?

A file descriptor is an unsigned integer used by a process to identify an open file. The number of file descriptors available to a process is limited by the /OPEN_MAX control in the sys/limits. h file. The number of file descriptors is also controlled by the ulimit -n flag.

What is the file descriptor in C?

What is the File Descriptor? File descriptor is integer that uniquely identifies an open file of the process. File Descriptor table: File descriptor table is the collection of integer array indices that are file descriptors in which elements are pointers to file table entries.


1 Answers

This is a rather hacky way around it but it works!

function fd($realpath) {
  $dir = '/proc/self/fd/';
  if ($dh = opendir($dir)) {
      while (($file = readdir($dh)) !== false) {
          $filename = $dir . $file;
          if (filetype($filename) == 'link' && realpath($filename) == $realpath) {
            closedir($dh);
            return $file;
          }
      }
      closedir($dh);
  }
  return FALSE;
}
like image 124
Josh Waihi Avatar answered Oct 20 '22 13:10

Josh Waihi