-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
74 lines (70 loc) · 1.12 KB
/
server.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
#include <unistd.h>
#include <stdio.h>
//#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
struct Treq
{
long mtype;
pid_t pid;
float a,b;
char op;
};
struct Tans
{
long mtype;
float res;
};
int main(int argc, char * argv[])
{
printf("Server started\n");
key_t key = ftok("server.c", 1234);
int id = msgget(key, IPC_CREAT|0666);
int n = sizeof(struct Treq) - sizeof(long);
int m = sizeof(struct Tans) - sizeof(long);
int rcvid;
struct Treq req;
struct Tans ans;
for(;;)
{
rcvid = msgrcv(id, &req, n, 1, 0);
if(rcvid == -1)
{
printf("No requests\n");
}
else
{
printf("Request received\n");
ans.mtype = req.pid;
switch(req.op)
{
case '+':
ans.res = req.a + req.b;
break;
case '-':
ans.res = req.a - req.b;
break;
case '*':
ans.res = req.a * req.b;
break;
case '/':
if(req.b == 0)
{
ans.res = atof("NaN");
}
else
{
ans.res = req.a / req.b;
}
break;
default:
break;
}
msgsnd(id, &ans, m, 0);
printf("Answer sent\n");
}
}
return 0;
}