-
Notifications
You must be signed in to change notification settings - Fork 9
/
myspin1.c
115 lines (98 loc) · 2.21 KB
/
myspin1.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
* myspin1 - Shell lab test program.
*
* When called by the shell driver, it synchronizes using a two-way
* handshake. This allows the driver to know that the job is available
* to receive signals. If it doesn't hear from the driver after some
* period of time, then it times out and terminates.
*
* When called standalone, it sleeps for [secs] seconds and then
* exits. If no argument is given, it sleeps for a default number
* of seconds.
*
* Usage: ./myspin1 [secs]
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <string.h>
#include "config.h"
char buf[MAXBUF];
int syncfd;
void sigalrm_handler(int signum)
{
exit(0);
}
void sigterm_handler(int signum)
{
int rc;
char *cmdp;
printf("Took SIGTERM!\n");
fflush(stdout);
cmdp = "";
if ((rc = recv(syncfd, buf, MAXBUF, 0)) < 0) {
perror("recv");
exit(1);
}
if ((rc = send(syncfd, cmdp, strlen(cmdp), 0)) < 0) {
perror("send");
exit(1);
}
exit(0);
}
int main(int argc, char **argv)
{
int rc;
int standalone;
char *str;
char *cmdp;
struct stat stat;
signal(SIGALRM, sigalrm_handler);
signal(SIGTERM, sigterm_handler);
/*
* Determine if the shell is running standalone or under the
* control of the driver program. If running under the driver, get
* the number of the driver's synchronizing domain socket
* descriptor.
*/
standalone = 1;
if ((str = getenv("SYNCFD")) != NULL) {
syncfd = atoi(str); /* Get descriptor number */
if (fstat(syncfd, &stat) != -1) /* Is is open? */
standalone = 0;
}
/*
* If the job is being run by the driver, then synchronize with
* the driver over its synchronizing domain socket. Ignore any
* command line argument.
*/
if (!standalone) {
alarm(JOB_TIMEOUT);
cmdp = "";
if ((rc = send(syncfd, cmdp, strlen(cmdp), 0)) < 0) {
perror("send");
exit(1);
}
if ((rc = recv(syncfd, buf, MAXBUF, 0)) < 0) {
perror("recv");
exit(1);
}
exit(0);
}
/*
* Otherwise spin until timing out
*/
else {
if (argc > 1)
alarm(atoi(argv[1]));
else
alarm(JOB_TIMEOUT);
while(1);
}
/* Control should never reach here */
exit(1);
}