C语言 如何从文件描述符中获取文件名和路径



我正在为linux开发一个C应用程序,我需要使用进程ID打开的文件列表。我正在遍历/proc/pid/fd目录以获取文件描述符。但是我如何从文件描述符中知道文件路径和文件名呢?或者我应该使用任何其他方法或 api 函数?

谢谢

手册将/proc/pid/fd/描述为:

这是一个子目录,每个文件包含一个条目 进程已打开,由其文件描述符命名,以及 这是指向实际文件的符号链接。

因此,您可以对每个条目调用stat并检索有关文件的元数据。

您可以使用

fcntlF_GETPATH

法典:

#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);
        }

输出:

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

参考:另一篇文章

最新更新