使用libblkid查找分区的UUID [英] Using libblkid to find UUID of a partition

查看:112
本文介绍了使用libblkid查找分区的UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 libblkid ,对文档感到困惑.有人可以给我提供一个示例,说明如何使用该库查找Linux根分区的UUID吗?

I was looking at libblkid and was confused about the documentation. Could someone provide me with an example of how I could find the UUID of a root linux partition using this library?

推荐答案

它几乎与手册中看起来的一样简单:创建一个探针结构,对其进行初始化,要求其提供一些信息,然后释放它.您可以将前两个步骤组合为一个.这是一个工作程序:

It's pretty much as simple as the manual makes it look: you create a probe structure, initialize it, ask it for some information, and then free it. And you can combine the first two steps into one. This is a working program:

#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <blkid/blkid.h>

int main (int argc, char *argv[]) {
  blkid_probe pr;
  const char *uuid;

  if (argc != 2) {
    fprintf(stderr, "Usage: %s devname\n", argv[0]);
    exit(1);
  }

  pr = blkid_new_probe_from_filename(argv[1]);
  if (!pr) {
    err(2, "Failed to open %s", argv[1]);
  }

  blkid_do_probe(pr);
  blkid_probe_lookup_value(pr, "UUID", &uuid, NULL);

  printf("UUID=%s\n", uuid);

  blkid_free_probe(pr);

  return 0;
}

blkid_probe_lookup_value 设置 uuid 指向属于 pr 结构的字符串,这就是为什么该参数为类型的原因const char * .如果需要,可以将其复制到您自己管理的 char * 中,但是只需传递给 printf ,就不需要了. blkid_probe_lookup_value 的第四个参数使您可以获取返回值的长度(以防万一). blkid_do_probe blkid_do_safeprobe blkid_do_fullprobe 之间有一些细微的区别,但是如果设备具有已知的文件系统而您只想拉从其中取出UUID,并从 blkid_do_probe 中获取第一个结果.

blkid_probe_lookup_value sets uuid to point to a string that belongs to the pr structure, which is why the argument is of type const char *. If you needed to, you could copy it to a char * that you manage on your own, but for just passing to printf, that's not needed. The fourth argument to blkid_probe_lookup_value lets you get the length of the returned value in case you need that as well. There are some subtle differences between blkid_do_probe, blkid_do_safeprobe, and blkid_do_fullprobe, but in cases where the device has a known filesystem and you just want to pull the UUID out of it, taking the first result from blkid_do_probe should do.

这篇关于使用libblkid查找分区的UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆