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

ЗАМЕЧАНИЕ. Справочная страница GNU/Linux flock(2) предупреждает, что блокировки flock() не работают для смонтированных удаленных файлов. Блокировки fcntl() работают, при условии, что у вас достаточно новая версия Linux и сервер NFS поддерживает блокировки файлов

<p>14.2.4. Обязательная блокировка</p>

Большинство коммерческих систем Unix поддерживают в дополнение к вспомогательной обязательную блокировку файлов. Обязательная блокировка работает лишь с fcntl(). Обязательная блокировка файла контролируется установками прав доступа файла, в частности, путем добавления к файлу бита setgid с помощью команды chmod.

$ echo hello, world > myfile /* Создать файл */

$ ls -l myfile /* Отобразить права доступа */

-rw-r--r-- 1 arnold devel 13 Apr 3 17:11 myfile

$ chmod g+s myfile /* Добавить бит setgid */

$ ls -l myfile /* Показать новые права доступа */

-rw-r-Sr-- 1 arnold devel 13 Apr 3 17:11 myfile

Бит права на исполнение группой должен быть оставлен сброшенным. S показывает, что бит setgid установлен, но что бит права на исполнение — нет; если бы были установлены оба бита, была бы использована строчная буква s.

Комбинация установленного бита setgid и сброшенного бита права на исполнение группой обычно бессмысленно. По этой причине, она была выбрана разработчиками System V для обозначения «использования обязательного блокирования». И в самом деле, добавления этого бита достаточно, чтобы заставить коммерческую систему Unix, такую как Solaris, использовать блокировку файлов.

На системах GNU/Linux несколько другая история. Для обязательных блокировок файл должен иметь установленный бит setgid, но этого одного недостаточно. Файловая система, содержащая файл, также должна быть смонтирована с опцией mand в команде mount.

Мы уже рассмотрели файловые системы, разделы диска, монтирование и команду mount, главным образом, в разделе 8.1 «Монтирование и демонтирование файловых систем». Мы можем продемонстрировать обязательную блокировку с помощью небольшой программы и файловой системой для тестирования на гибком диске. Для начала, вот программа:

1  /* ch14-lockall.c --- Демонстрация обязательной блокировки. */

2

3  #include /* для fprintf(), stderr, BUFSIZ */

4  #include /* объявление errno */

5  #include /* для флагов open() */

6  #include /* объявление strerror() */

7  #include /* для ssize_t */

8  #include

9  #include /* для mode_t */

10

11 int

12 main(int argc, char **argv)

13 {

14  int fd;

15  int i, j;

16  mode_t rw_mode;

17  static char message[] = "hello, world\n";

18  struct flock lock;

19

20  if (argc != 2) {

21   fprintf(stderr, "usage: %s file\n", argv[0]);

22   exit(1);

23  }

24

25  rw_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; / * 0644 */

26  fd = open(argv[1], O_RDWR|O_TRUNC|O_CREAT|O_EXCL, rw_mode);

27  if (fd < 0) {

28   fprintf(stderr, "%s: %s: cannot open for read/write: %s\n",

29    argv[0], argv[1], strerror(errno));

30   (void)close(fd);

31   return 1;

32  }

33

34  if (write(fd, message, strlen(message)) != strlen(message)) {

35   fprintf(stderr, "%s: %s: cannot write: %s\n",

36    argv[0], argv[1], strerror(errno));

37   (void)close(fd);

38   return 1;

39  }

40

41  rw_mode |= S_ISGID; /* добавить бит обязательной блокировки */

42

43  if (fchmod(fd, rw_mode) < 0) {

44   fprintf(stderr, "%s: %s: cannot change mode to %o: %s\n",

Перейти на страницу:

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

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

Стивен Прата

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