-
Notifications
You must be signed in to change notification settings - Fork 5
/
local_server.cc
104 lines (83 loc) · 1.91 KB
/
local_server.cc
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
#if defined(LINUX)
#include <errno.h>
#include <unistd.h>
#define die perror
#define SERVER "/tmp/serversocket"
#else
#include "types.h"
#include "user.h"
#include "pthread.h"
#define SERVER "/serversocket"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#define MAXMSG 512
#define MESSAGE "ni hao"
int sock;
int
make_named_socket(const char *filename)
{
struct sockaddr_un name;
int sock;
size_t size;
sock = socket (PF_LOCAL, SOCK_DGRAM, 0);
if (sock < 0) {
die ("socket");
}
name.sun_family = AF_LOCAL;
strncpy (name.sun_path, filename, sizeof (name.sun_path));
name.sun_path[sizeof (name.sun_path) - 1] = '\0';
size = SUN_LEN (&name);
if (bind (sock, (struct sockaddr *) &name, size) < 0) {
die ("bind");
}
return sock;
}
static void*
thread(void* x)
{
int id = (uintptr_t)x;
char message[MAXMSG];
struct sockaddr_un name;
socklen_t size;
int nbytes;
while (1)
{
size = sizeof (name);
nbytes = recvfrom (sock, message, MAXMSG, 0,
(struct sockaddr *) & name, &size);
if (nbytes < 0) {
die ("recfrom (server)");
}
if (strcmp(message, "Hello, local socket server?") != 0) {
printf("%d: message %s\n", id, message);
die ("data is incorrect (server)");
}
strcpy(message, MESSAGE);
nbytes = sendto (sock, message, strlen(MESSAGE)+1, 0,
(struct sockaddr *) & name, size);
if (nbytes < 0)
{
die ("sendto (server)");
}
}
}
int
main (int argc, char *argv[])
{
pthread_t tid;
int nthread;
unlink (SERVER);
if (argc < 2)
die("usage: %s nthreads", argv[0]);
nthread = atoi(argv[1]);
sock = make_named_socket (SERVER);
for (int i = 0; i < nthread; i++)
pthread_create(&tid, nullptr, thread, (void*)(long)i);
for (int i = 0; i < nthread; i++)
wait(NULL);
return 0;
}