File: fetch-first-sector.c

package info (click to toggle)
libnbd 1.24.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,956 kB
  • sloc: ansic: 55,158; ml: 12,325; sh: 8,811; python: 4,757; makefile: 3,038; perl: 165; cpp: 24
file content (66 lines) | stat: -rw-r--r-- 1,444 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* This example shows how to connect to an NBD server
 * and fetch and print the first sector (usually the
 * boot sector or partition table or filesystem
 * superblock).
 *
 * You can test it with nbdkit like this:
 *
 * nbdkit -U - floppy . \
 *   --run './fetch-first-sector $unixsocket'
 *
 * The nbdkit floppy plugin creates an MBR disk so the
 * first sector is the partition table.
 */

#include <stdio.h>
#include <stdlib.h>

#include <libnbd.h>

int
main (int argc, char *argv[])
{
  struct nbd_handle *nbd;
  char buf[512];
  FILE *pp;

  if (argc != 2) {
    fprintf (stderr, "%s socket\n", argv[0]);
    exit (EXIT_FAILURE);
  }

  /* Create the libnbd handle. */
  nbd = nbd_create ();
  if (nbd == NULL) {
    fprintf (stderr, "%s\n", nbd_get_error ());
    exit (EXIT_FAILURE);
  }

  /* Connect to the NBD server over a
   * Unix domain socket.
   */
  if (nbd_connect_unix (nbd, argv[1]) == -1) {
    fprintf (stderr, "%s\n", nbd_get_error ());
    exit (EXIT_FAILURE);
  }

  /* Read the first sector synchronously. */
  if (nbd_pread (nbd, buf, sizeof buf, 0, 0) == -1) {
    fprintf (stderr, "%s\n", nbd_get_error ());
    exit (EXIT_FAILURE);
  }

  /* Close the libnbd handle. */
  nbd_close (nbd);

  /* Print the first sector. */
  pp = popen ("hexdump -C", "w");
  if (pp == NULL) {
    perror ("popen: hexdump");
    exit (EXIT_FAILURE);
  }
  fwrite (buf, sizeof buf, 1, pp);
  pclose (pp);

  exit (EXIT_SUCCESS);
}