Книга: Programming with POSIX® Threads

1.5.1 The baseline, synchronous version

1.5.1 The baseline, synchronous version

1 Include the header file errors.h, which includes standard headers like <unistd.h> and <stdio.h> and defines error reporting macros that are used throughout the examples in this book. We don't use the error reporting macros in this particular example, but consistency is nice, sometimes.

9-26 The "baseline" version, alarm.c, is a synchronous alarm program with a single routine, main. Most of main is a loop, which processes simple commands until fgets returns a NULL (error or end of file). Each line is "parsed" with sscanf to separate the number of seconds to wait (%d, the first sequence of digits) from the message string to print (%64 [^n], the rest of the line, up to 64 characters excluding newline).

? alarm.c

1 #include "errors.h" 2
3 int main (int argc, char *argv[])
4 {
5 int seconds;
6 char line[128];
7 char message[64]; 8
9 while (1) {
10 printf ("Alarm> ");
11 if (fgets (line, sizeof (line), stdin) == NULL) exit (0);
12 if (strlen (line) <= 1) continue; 13
14 /*
15 * Parse input line into seconds (%d) and a message
16 * (%64[^n]), consisting of up to 64 characters
17 * separated from the seconds by whitespace.
18 */
19 if (sscanf (line, "%d %64[^n]",
20 &seconds, message) < 2) {
21 fprintf (stderr, "Bad commandn");
22 } else {
23 sleep (seconds);
24 printf ("(%d) %sn", seconds, message);
25 }
26 }
27 }

The problem with the program alarm.c is that only one alarm request can be active at a time. If you set an alarm to remind you to do something in 10 minutes (600 seconds), you can't decide to have it remind you of something else in 5 minutes. The program is doing something synchronously that you would probably like to be asynchronous.

Оглавление книги


Генерация: 1.356. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз