【问题标题】:How To: Obtain the device node of the device containing a file, given the file descriptor如何:在给定文件描述符的情况下,获取包含文件的设备的设备节点
【发布时间】:2014-06-12 14:46:33
【问题描述】:

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

【问题讨论】:

    标签: c++ linux file-descriptor udev device-node


    【解决方案1】:

    这可以使用libudevfstat 轻松实现。

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

    【讨论】:

    • 您不会检查 任何 函数调用的错误。这不是很好的示例代码。
    • 我不检查错误以使示例更短。我不同意这不是一个好的示例代码,因为它显示了实现获取设备节点目标的路径。不是一段好的生产代码,但肯定是一个很好的例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多