-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path44-4-changed_server_with_sig.c
69 lines (56 loc) · 2.13 KB
/
44-4-changed_server_with_sig.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
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include "fifo_seqnum.h"
void handler(int sig)
{
unlink(SERVER_FIFO);
exit(EXIT_SUCCESS);
}
int
main(int argc, char *argv[])
{
int serverFd, dummyFd, clientFd;
char clientFifo[CLIENT_FIFO_NAME_LEN];
struct request req;
struct response resp;
int seqNum = 0; /* This is our "service" */
/* Create well-known FIFO, and open it for reading */
umask(0); /* So we get the permissions we want */
if (mkfifo(SERVER_FIFO, S_IRUSR | S_IWUSR | S_IWGRP) == -1
&& errno != EEXIST)
errExit("mkfifo %s", SERVER_FIFO);
signal(SIGINT, handler);
signal(SIGTERM, handler);
serverFd = open(SERVER_FIFO, O_RDONLY);
if (serverFd == -1)
errExit("open %s", SERVER_FIFO);
/* Open an extra write descriptor, so that we never see EOF */
dummyFd = open(SERVER_FIFO, O_WRONLY);
if (dummyFd == -1)
errExit("open %s", SERVER_FIFO);
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) errExit("signal");
for (;;) { /* Read requests and send responses */
if (read(serverFd, &req, sizeof(struct request))
!= sizeof(struct request)) {
fprintf(stderr, "Error reading request; discarding\n");
continue; /* Either partial read or error */
}
/* Open client FIFO (previously created by client) */
snprintf(clientFifo, CLIENT_FIFO_NAME_LEN, CLIENT_FIFO_TEMPLATE,
(long) req.pid);
clientFd = open(clientFifo, O_WRONLY);
if (clientFd == -1) { /* Open failed, give up on client */
errMsg("open %s", clientFifo);
continue;
}
/* Send response and close FIFO */
resp.seqNum = seqNum;
if (write(clientFd, &resp, sizeof(struct response))
!= sizeof(struct response))
fprintf(stderr, "Error writing to FIFO %s\n", clientFifo);
if (close(clientFd) == -1)
errMsg("close");
seqNum += req.seqLen; /* Update our sequence number */
}
}