Читаем Programming with POSIX® Threads полностью

The program atfork.c shows the use of fork handlers. When run with no argument, or with a nonzero argument, the program will install fork handlers. When run with a zero argument, such as atfork 0, it will not.

With fork handlers installed, the result will be two output lines reporting the result of the fork call and, in parentheses, the pid of the current process. Without fork handlers, the child process will be created while the initial thread owns the mutex. Because the initial thread does not exist in the child, the mutex cannot be unlocked, and the child process will hang — only the parent process will print its message.

13-25 Function fork_prepare is the prepare handler. This will be called by fork, in the parent process, before creating the child process. Any state changed by this function, in particular, mutexes that are locked, will be copied into the child process. The fork_prepare function locks the program's mutex.

31-42 Function fork_parent is the parent handler. This will be called by fork, in the parent process, after creating the child process. In general, a parent handler should undo whatever was done in the prepare handler, so that the parent process can continue normally. The fork_parent function unlocks the mutex that was locked by fork_prepare.

48-60 Function fork_child is the child handler. This will be called by fork, in the child process. In most cases, the child handler will need to do whatever was done in the fork_parent handler to "unlock" the state so that the child can continue. It may also need to perform additional cleanup, for example, fork_child sets the self_pid variable to the child process's pid as well as unlocking the process mutex.

65-91 After creating a child process, which will continue executing the thread_ routine code, the thread_routine function locks the mutex. When run with fork handlers, the fork call will be blocked (when the prepare handler locks the mutex) until the mutex is available. Without fork handlers, the thread will fork before main unlocks the mutex, and the thread will hang in the child at this point. 99-106 The main program declares fork handlers unless the program is run with an argument of 0.

108-123 The main program locks the mutex before creating the thread that will fork. It then sleeps for several seconds, to ensure that the thread will be able to call fork while the mutex is locked, and then unlocks the mutex. The thread running thread_routine will always succeed in the parent process, because it will simply block until main releases the lock.

However, without the fork handlers, the child process will be created while the mutex is locked. The thread (main) that locked the mutex does not exist in the child, and cannot unlock the mutex in the child process. Mutexes can be unlocked

in the child only if they were locked by the thread that called fork — and fork handlers provide the best way to ensure that.

atfork.c

1 #include

2 #include

3 #include

4 #include "errors.h"

5

6 pid_t self_pid; /* pid of current process */

7 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

8

9 /*

10 * This routine will be called prior to executing the fork,

11 * within the parent process.

12 */

13 void fork_prepare (void)

14 {

15 int status;

16

17 /*

18 * Lock the mutex in the parent before creating the child,

19 * to ensure that no other thread can lock it (or change any

20 * associated shared state) until after the fork completes.

21 */

22 status = pthread_mutex_lock (&mutex);

23 if (status != 0)

24 err_abort (status, "Lock in prepare handler");

25 }

26

27 /*

28 * This routine will be called after executing the fork, within

29 * the parent process

30 */

31 void fork_parent (void)

32 {

33 int status;

34

35 /*

36 * Unlock the mutex in the parent after the child has been

37 * created.

38 */

39 status = pthread_mutex_unlock (&mutex);

40 if (status != 0)

41  err_abort (status, "Unlock in parent handler");

42 }

43

44 /*

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

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

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

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