Читаем Linux программирование в примерах полностью

 int mnt_freq;     /* Частота дампа (в днях). */

 int mnt_passno;    /* Номер для 'fsck'. */

};

Обычным принципом работы со смонтированными файловыми системами является создание внешнего цикла, читающего /etc/mtab, обрабатывая по одной struct mntent за раз. Наш первый пример, ch08-mounted.c, делает именно это:

1  /* ch08-mounted.с --- вывод списка смонтированных файловых

2     систем */

3  /* ЗАМЕЧАНИЕ: специфично для GNU/Linux! */

4

5  #include

6  #include

7  #include /* для getmntent() и др. */

8  #include /* для getopt() */

9

10 void process(const char *filename);

11 void print_mount(const struct mntent *fs);

12

13 char *myname;

14

15 /* main --- обработка опций */

16

17 int main(int argc, char **argv)

18 {

19  int c;

20  char *file = "/etc/mtab"; /* файл по умолчанию для чтения */

21

22  myname = argv[0];

23  while ((c = getopt(argc, argv, "f:")) != -1) {

24   switch (c) {

25   case 'f':

26    file = optarg;

27    break;

28   default:

29    fprintf(stderr, "usage: %s [-f fstab-file]\n", argv[0]);

30    exit(1);

31   }

32  }

33

34  process(file);

35  return 0;

36 }

37

38 /* process --- прочесть структуры struct mntent из файла */

39

40 void process(const char *filename)

41 {

42  FILE *fp;

43  struct mntent *fs;

44

45  fp = setmntent(filename, "r"); /* только для чтения */

46  if (fp == NULL) {

47   fprintf(stderr, "%s: %s: could not open: %s\n",

48    myname, filename, strerror(errno));

49   exit(1);

50  }

51

52  while ((fs = getmntent(fp)) != NULL)

53   print_mount(fs);

54

55  endmntent(fp);

56 }

57

58 /* print_mount --- вывод одного смонтированного элемента */

59

60 void print_mount(const struct mntent *fs)

61 {

62  printf("%s %s %s %s %d %d\n",

63   fs->mnt_fsname,

64   fs->mnt_dir,

65   fs->mnt_type,

66   fs->mnt_opts,

67   fs->mnt_freq,

68   fs->mnt_passno);

69 }

В отличие от большинства программ, которые мы до сих пор видели, эта специфична для Linux. Во многих Unix-системах есть схожие процедуры, но их идентичность не гарантируется.

По умолчанию, ch08-mounted читает /etc/mtab, выводя сведения о каждой смонтированной файловой системе. Опция -f позволяет указать другой файл для чтения, такой, как /proc/mounts или даже /etc/fstab.

Функция main() обрабатывает командную строку (строки 23–32) и вызывает для указанного файла process(). (Эта программа следует нашему стандартному шаблону.)

process(), в свою очередь, открывает файл (строка 45) и проходит в цикле через каждую возвращённую файловую систему (строки 52–53). После завершения она закрывает файл (строка 55).

Функция print_mount() выводит информацию из struct mnent. Вывод во многом напоминает вывод 'cat /etc/mtab':

$ ch08-mounted /* Запуск программы */

/dev/hda2 / ext3 rw 0 0

none /proc proc rw 0 0

usbdevfs /proc/bus/usb usbdevfs rw 0 0

/dev/hda5 /d ext3 rw 0 0

none /dev/pts devpts rw,gid=5,mode=620 0 0

none /dev/shm tmpfs rw 0 0

none /proc/sys/fs/binfmt_misc binfmt_misc rw 0 0

/dev/hda1 /win vfat rw,noexec,nosuid,nodev,uid=2076,gid=10,user=arnold 0 0

<p>8.3. Получение сведений о файловой системе</p>
Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных