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

54   manage(si); /* обработать то, что произошло */

55  } else if (ret > 0) {

56   strcpy(buf, "\treaped unexpected pid ");

57   strcat(buf, format_num(ret));

58   strcat(buf, "\n");

59   write(1, buf, strlen(buf));

60   goto retry; /* почему бы нет? */

61  } else if (ret == 0) {

62   strcpy(buf, "\tpid ");

63   strcat(buf, format_num(si->si_pid));

64   strcat(buf, " changed status\n");

65   write(1, buf, strlen(buf));

66   manage(si); /* обработать то, что произошло */

67  } else if (ret == -1 && errno == EINTR) {

68   write(1, "\tretrying\n", 10);

69   goto retry;

70  } else {

71   strcpy(buf, "\twaitpid() failed: ");

72   strcat(buf, strerror(errno));

73   strcat(buf, "\n");

74   write(1, buf, strlen(buf));

75  }

76

77  write(1, exited, strlen(exited));

78 }

Обработчик сигнала похож на показанные ранее. Обратите внимание на список аргументов (строка 39) и на то, что нет цикла.

Строки 49–54 обрабатывают завершение процесса, включая вызов manage() для вывода состояния.

Строки 55–60 обрабатывают случай неожиданного завершения потомка. Этого не должно происходить, поскольку обработчику сигнала передается специфическая для определенного порожденного процесса информация.

Строки 61–66 представляют для нас интерес: возвращаемое значение для изменений состояния равно 0. manage() имеет дело с деталями (строка 66).

Строки 67–69 обрабатывают прерывания, а строки 70–75 распоряжаются ошибками

80 /* child --- что сделать в порожденном процессе */

81

82 void child(void)

83 {

84  raise(SIGCONT); /* должен быть проигнорирован */

85  raise(SIGSTOP); /* заснуть, родитель снова разбудит */

86  printf("\t---> child restarted <---\n");

87  exit(42); /* нормальное завершение, дать возможность родителю получить значение */

88 }

Функция child() обрабатывает поведение порожденного процесса, предпринимая действия для уведомления родителя[113]. Строка 84 посылает SIGCONT, что может вызвать получение родителем события CLD_CONTINUED. Строка 85 посылает SIGSTOP, который останавливает процесс (сигнал не может быть перехвачен) и вызывает для родителя событие CLD_STOPPED. Когда родитель возобновляет порожденный процесс, последний выводит сообщение, что он снова активен, а затем завершается с известным статусом завершения.

90  /* main --- установка относящихся к порожденному процессу сведений

       и сигналов, создание порожденного процесса */

91

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

93  {

94   pid_t kid;

95   struct sigaction sa;

96   sigset_t childset, emptyset;

97

98   sigemptyset(∅);

99

100  sa.sa_flags = SA_SIGINFO;

101  sa.sa_sigaction = childhandler;

102  sigfillset(&sa.sa_mask); /* при вызове обработчика все заблокировать */

103  sigaction(SIGCHLD, &sa, NULL);

104

105  sigemptyset(&childset);

106  sigaddset(&childset, SIGCHLD);

107

108  sigprocmask(SIG_SETMASK, &childset, NULL); /* блокировать его в коде main */

109

110  if ((kid = fork()) == 0)

111   child();

112

113  /* здесь выполняется родитель */

114  for (;;) {

115   printf("waiting for signals\n");

116   sigsuspend(∅);

117  }

118

119  return 0;

120 }

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

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

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

Стивен Прата

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