-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathipc.c
131 lines (101 loc) · 2.18 KB
/
ipc.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <poll.h>
#include "ipc.h"
#define IPCDIR "/home/denis/ipc"
int ipcopen(char *myname)
{
struct sockaddr_un addr={AF_UNIX, IPCDIR};
int sfd;
if(!myname)
{
printf("Error: no local IPC address\n");
return -1;
}
strcpy(addr.sun_path+strlen(IPCDIR), myname);
sfd=socket(AF_UNIX, SOCK_DGRAM, 0);
if(sfd==-1)
{
printf("Error: Unable to create a socket: %s\n", strerror(errno));
return -1;
}
unlink(addr.sun_path);
if(bind(sfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)))
{
printf("Error: Unable to bind a socket: %s\n", strerror(errno));
close(sfd);
return -1;
}
return sfd;
}
int ipcsend(int sfd, char *buf, int size, const char *dest)
{
static struct sockaddr_un addr = {AF_UNIX, IPCDIR};
if(!dest)
{
printf("Error: No dest address\n");
return -1;
}
strcpy(addr.sun_path+strlen(IPCDIR), dest);
if(sendto(sfd, buf, size, 0, (struct sockaddr*)&addr, sizeof(struct sockaddr_un))==-1)
{
printf("Error: Unable to send the message to %s: %s\n", dest, strerror(errno));
return -1;
}
return 0;
}
int ipcrecv(int sfd, char *buf, int size)
{
int i=recv(sfd, buf, size, 0);
if(i==-1)
printf("Error: recv: %s\n", strerror(errno));
return i;
}
int ipcclose(int sfd)
{
if(close(sfd)==-1)
{
printf("Error: close: %s\n", strerror(errno));
return -1;
}
return 0;
}
int ipcsendmsg(int sfd, isomessage *message, const char *dest)
{
static char buf[1000];
int size;
size=message->ByteSize();
if(size>sizeof(buf))
{
printf("Error: Message is too big (%d bytes)\n", size);
return 0;
}
if(!message->SerializeWithCachedSizesToArray((google::protobuf::uint8*)buf))
{
printf("Error: Unable to serialize the message\n");
return 0;
}
if(ipcsend(sfd, buf, size, dest)==-1)
{
printf("Error: Unable to send the message\n");
return -1;
}
return size;
}
int ipcrecvmsg(int sfd, isomessage *message)
{
static char buf[1000];
int size;
size=ipcrecv(sfd, buf, sizeof(buf));
if(size==-1)
return -1;
if(!message->ParseFromArray(buf, size))
{
printf("Warning: Unable to de-serialize the message\n");
return 0;
}
return size;
}