0

I am developing a C application for linux in which I need the open file lists using process ids. I am traversing /proc/pid/fd directory for file descriptor. But how can I know file path and file name from file descriptor? Or any other method or api function should I use?

Thanks,

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
techfun
  • 913
  • 2
  • 13
  • 25

2 Answers2

3

The manual describes /proc/pid/fd/ as:

This is a subdirectory containing one entry for each file which the process has open, named by its file descriptor, and which is a symbolic link to the actual file.

Therefore, you can call stat on each entry and retrieve metadata about the file.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • If you want information about the link, you need lstat, not stat. – user3303729 Feb 15 '14 at 00:03
  • `touch foo;` [process opens foo]; `ln foo bar`; [`foo` and `bar` point to the same file content now ]; `rm foo` ; [/proc/pid/fd/XX symlink is dead now, though the file itself is still accessible as `bar`]; – ArtemB Feb 15 '14 at 00:26
  • @ArtemB: That's right, you cannot access those "walking dead" files from outside the process that owns it (imagine you didn't even have `bar`). I believe that's by design, for security reasons. – Kerrek SB Feb 15 '14 at 00:43
  • @KerrekSB : What about HP-UX or Solaris? – user2284570 Jun 02 '15 at 01:25
0

you can use: fcntl's F_GETPATH

code:

#include <sys/syslimits.h>
#include <fcntl.h>

const char* curDir = "/private/var/mobile/Library/“;

int curDirFd = open(curDir, O_RDONLY);

        // for debug: get file path from fd
        char filePath[PATH_MAX];
        int fcntlRet = fcntl(curDirFd, F_GETPATH, filePath);
        const int FCNTL_FAILED = -1;
        if (fcntlRet != FCNTL_FAILED){
            NSLog(@"fcntl OK: curDirFd=%d -> filePath=%s", curDirFd, filePath);
        } else {
            NSLog(@"fcntl fail for curDirFd=%d", curDirFd);
        }

output:

curDir=/private/./var/../var/mobile/Library/./ -> curDirFd=4
fcntl OK: curDirFd=4 -> filePath=/private/var/mobile/Library

refer: another post

crifan
  • 12,947
  • 1
  • 71
  • 56