-
Notifications
You must be signed in to change notification settings - Fork 63
/
alarm_fork.c
56 lines (53 loc) · 1.56 KB
/
alarm_fork.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* alarm_fork.c
*
* This version of alarm.c uses fork to create a new process to
* wait for each alarm to expire.
*/
#include <sys/types.h>
#include <wait.h>
#include "errors.h"
int main (int argc, char *argv[])
{
int status;
char line[128];
int seconds;
pid_t pid;
char message[64];
while (1) {
printf ("Alarm> ");
if (fgets (line, sizeof (line), stdin) == NULL) exit (0);
if (strlen (line) <= 1) continue;
/*
* Parse input line into seconds (%d) and a message
* (%64[^\n]), consisting of up to 64 characters
* separated from the seconds by whitespace.
*/
if (sscanf (line, "%d %64[^\n]",
&seconds, message) < 2) {
fprintf (stderr, "Bad command\n");
} else {
pid = fork ();
if (pid == (pid_t)-1)
errno_abort ("Fork");
if (pid == (pid_t)0) {
/*
* If we're in the child, wait and then print a message
*/
sleep (seconds);
printf ("(%d) %s\n", seconds, message);
exit (0);
} else {
/*
* In the parent, call waitpid() to collect any children that
* have already terminated.
*/
do {
pid = waitpid ((pid_t)-1, NULL, WNOHANG);
if (pid == (pid_t)-1)
errno_abort ("Wait for child");
} while (pid != (pid_t)0);
}
}
}
}