如何:给定文件描述符,获取包含文件的设备的设备节点

How To: Obtain the device node of the device containing a file, given the file descriptor

本文关键字:文件 包含 节点 获取 描述 如何      更新时间:2023-10-16

就是这么简单。我有一个打开的文件的文件描述符,我想知道包含它的设备的节点名。

这可以通过使用libdev和fstat轻松实现。

#include <libudev.h>   // udev headers.
#include <sys/stat.h>  // for fstat function and stat struct.
#include <iostream>    // for printing ouput.
#include <fcntl>       // for open function.
using namespace std;
int main(int argc, char *argv[])
{
    int fd = open(argv[1], O_RDONLY);  // The file can be opened using any other mode, Eg. O_RDWR, O_APPEND, etc...
    struct udev *udev = udev_new();
    struct stat tb;
    fstat(fd, &tb);
    struct udev_device* dev = udev_device_new_from_devnum(udev, 'b', tb.st_dev);
    cout << "The opened file is located in the device: " << udev_device_get_devnode(dev) << endl;
    return 0;
}