简体   繁体   中英

How can I get file name and path from file descriptor?

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,

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM