-
Notifications
You must be signed in to change notification settings - Fork 0
/
alarm_thread.c
76 lines (63 loc) · 1.5 KB
/
alarm_thread.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "errors.h"
typedef struct alarm_tag
{
int seconds;
char message[65];
}alarm_t;
void *alarm_func(void *args)
{
alarm_t *alarm = (alarm_t*)args;
int status = 0;
status = pthread_detach(pthread_self());
if (status != 0)
{
err_abort(status, "pthread_detach failed!");
}
sleep(alarm->seconds);
printf("(%d) %s\n", alarm->seconds, alarm->message);
free(alarm);
return NULL;
}
int main(void)
{
int status = 0;
char line[128];
alarm_t *alarm;
pthread_t thread;
while (1)
{
printf("Please enter the alarm time and message: ");
if (fgets(line, sizeof(line), stdin) == NULL)
{
return 0;
}
if (strlen(line)<=1)
continue;
alarm = (alarm_t*)malloc(sizeof(alarm_t));
if (alarm == NULL)
{
printf("Unable to allocate necessary memory!\n");
errno_abort("Unable to allocate necessary memory!");
}
if (sscanf(line, "%d %64[^\n]",
&alarm->seconds, alarm->message) < 2)
{
printf("Bad command entered!");
free (alarm);
return errno;
}
else
{
status = pthread_create(&thread, NULL, alarm_func, alarm);
if (status != 0)
{
errno_abort("Unable to create thread!");
}
}
}
return 1;
}