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

2216  unsigned i;

2217  sigemptyset(&caught_signals);

2218  for (i = 0; i < nsigs; i++) /* - Блокировать все сигналы */

2219   sigaddset(&caught_signals, sigs[i]);

2220  newact.sa_handler = sighandler; /* - Функция обработки сигнала */

2221  newact.sa_mask = caught_signals; /* - Установить для обработчика маску сигналов процесса */

2222  newact.sa_flags =0; /* - Особых флагов нет */

2223 }

2224 #endif

2225

2226 {

2227  unsigned i;

2228  for (i = 0; i < nsigs; i++) /* Для всех сигналов... */

2229  {

2230   int sig = sigs[i];

2231 #ifdef SA_NOCLDSTOP

2232   sigaction(sig, NULL, &oldact); /* - Получить старый обработчик */

2233   if (oldact.sa_handler != SIG_IGN) /* - Если этот сигнал не игнорируется */

2234    sigaction(sig, &newact, NULL); /* - Установить наш обработчик */

2235 #else

2236   if (signal(sig, SIG_IGN) != SIG_IGN)

2237    signal(sig, sighandler); /* - Та же логика со старым API */

2238 #endif

2239  }

2240 }

Мы заметили, что строки 2216–2219 и 2221 могут быть замещены одним вызовом: sigfillset(&newact.sa_mask);

Мы не знаем, почему код написан именно таким способом.

Интерес представляют также строки 2233–2234 и 2236–2237, которые показывают правильный способ проверки того, игнорируется ли сигнал, и для установки обработчика лишь в том случае, если сигнал не игнорируется.

ЗАМЕЧАНИЕ. Функции API sigaction() и signal() не должны использоваться вместе для одного и того же сигнала. Хотя POSIX идет на большие длинноты, чтобы сначала сделать возможным использование signal(), получить struct sigaction, представляющую диспозицию signal(), и восстановить ее, все равно это плохая мысль. Код будет гораздо проще читать, писать и понимать, если вы используете одну функцию или другую взаимоисключающим образам

10.6.5. Извлечение ожидающих сигналов: sigpending()

Описанный ранее системный вызов sigpending() позволяет получить набор ожидающих сигналов, т.е тех сигналов, которые появились, но еще не доставлены из-за блокировки:

#include /* POSIX */


int sigpending(sigset_t *set);

Помимо разблокировки ожидающих сигналов, чтобы они могли быть доставлены, вы можете решить их игнорировать. Установка действия сигнала SIG_IGN вызывает сбрасывание сигнала (даже если он был заблокирован). Сходным образом для тех сигналов, действием по умолчанию для которых является их игнорирование, установка действия в SIG_DFL также вызывает сбрасывание таких ожидающих сигналов.

10.6.6. Создание возможности для прерывания функций: siginterrupt()

Чтобы сделать определенную функцию прерываемой или повторно запускаемой в зависимости от значения второго аргумента, в качестве удобного средства может использоваться функция siginterrupt(). Объявление следующее:

#include /* XSI */


int siginterrupt(int sig, int flag);

В соответствии со стандартом POSIX поведение siginterrupt() эквивалентно следующему коду:

int siginterrupt(int sig, int flag) {

 int ret;

 struct sigaction act;

 (void)sigaction(sig, NULL, &act); /* Получить старые установки */

 if (flag) /* Если flag равен true... */

  act.sa_flags &= ~SA_RESTART; /* Запретить повторный запуск */

 else /* В противном случае... */

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

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

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

Стивен Прата

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