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

54   if (kids[i] == NOT_USED)

55    continue;

56

57 retry:

58  if ((ret = waitpid(kids[i], &status, WNOHANG)) == kids[i]) {

59   strcpy(buf, "\treaped process ");

60   strcat(buf, format_num(ret));

61   strcat(buf, "\n");

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

63   kids[i] = NOT_USED;

64   kidsleft--; /* <<< Добавлено */

65  } else if (ret == 0) {

    /* ...не изменившийся код пропущен... */

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

81 }

Это идентично предыдущей версии за тем исключением, что у нас есть новая переменная, kidsleft, указывающая, сколько имеется не опрошенных потомков. Строки 15 и 64 помечают новый код.

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

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

84

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

86  {

     /* ...не изменившийся код пропущен... */

100

101  sigemptyset(&childset);

102  sigaddset(&childset, SIGCHLD);

103

104  /* sigprocmask(SIG_SETMASK, &childset, NULL); /* блокирование в коде main */

105

106  for (nkids = 0; nkids < 5; nkids++) {

107   if ((kids[nkids] = fork()) == 0) {

108    sleep(3);

109    _exit(0);

110   }

111   kidsleft++; /* <<< Added */

112  }

113

114  /* sleep(5); /* дать потомкам шанс завершиться */

115

116  while (kidsleft > 0) { /* <<< Добавлено */

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

118   sigsuspend(∅);

119  } /* <<< Добавлено */

120

121  return 0;

122 }

Здесь код также почти идентичен. Строки 104 и 114 закомментированы из предыдущей версии, а строки 111, 116 и 119 добавлены. Удивительно, при запуске поведение меняется в зависимости от версии ядра!

$ uname -a /* Отобразить версию системы */

Linux example1 2.4.20-8 #1 Thu Mar 13 17:54:28 EST 2003 i686 i686 i386 GNU/Linux

$ ch10-reap2 /* Запустить программу */

waiting for signals

Entered childhandler /* Опрос одного потомка */

  reaped process 2702

  pid 2703 not available yet

  pid 2704 not available yet

  pid 2705 not available yet

  pid 27 06 not available yet

Exited childhandler

waiting for signals

Entered childhandler /* И следующего */

  reaped process 2703

  pid 2704 not available yet

  pid 2705 not available yet

  pid 2706 not available yet

Exited childhandler

waiting for signals

Entered childhandler /* И так далее */

  reaped process 2704

  pid 2705 not available yet

  pid 2706 not available yet

Exited childhandler

waiting for signals

Entered childhandler

  reaped process 2705

  pid 2706 not available yet

Exited childhandler

waiting for signals

Entered childhandler

  reaped process 2706

Exited childhandler

В данном примере на каждый процесс поступает ровно один SIGCHLD! Хотя это прекрасно и полностью воспроизводимо на этой системе, это также необычно. Как на более раннем, так и на более позднем ядре и на Solaris программа получает один сигнал для более чем одного потомка:

$ uname -a /* Отобразить версию системы */

Linux example2 2.4.22-1.2115.npt1 #1 Wed Oct 29 15:42:51 EST 2003 i686 i686 i386 GNU/Linux

$ ch10-reap2 /* Запуск программы */

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

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

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

Стивен Прата

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