forked from bangadennis/networking
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.c
87 lines (71 loc) · 1.9 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
** Server Program -- writes to a message queue
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
typedef struct msgbuffer {
long mtype;
char mtext[300];
}msgbuf;
int main(void)
{
msgbuf bufrecv;
msgbuf bufsnd;
int msqid;
key_t key;
int count=1;
//get the process id
long processid=getpid();
//Creating a unique key
if ((key = ftok("server.c", 'B')) == -1) {
perror("ftok");
exit(1);
}
//Initialize the message queue
if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
perror("msgget Initialization failed");
exit(1);
}
printf("Process ID : %ld\n", processid);
printf("Server Started Running:,Message Queue ID=%d \n [Cltrl+D to quit]:\n", msqid);
while(count>0) {
printf("To ID:\n");
scanf("%ld", &bufsnd.mtype);
//printf("Message:\n");
getchar();
printf("Message:\n");
fgets(bufsnd.mtext, sizeof bufsnd.mtext, stdin);
//scanf("%s", bufsnd.mtext);
//(void) strcpy(bufsnd.mtext, "Am the Boss--->>");
//message length
int len = strlen(bufsnd.mtext);
if(bufsnd.mtext[len-1]=='\n')
{
bufsnd.mtext[len-1]='\0';
}
if (msgsnd(msqid, &bufsnd, len+1, 0) == -1) {
perror("msgsnd failed");
exit(1);
}
printf("Message sent\n");
printf("********************************************\n");
if (msgrcv(msqid, &bufrecv, sizeof(bufrecv.mtext), 0, 0) == -1) {
perror("msgrcv failed");
exit(1);
}
//Message display
printf("Reply: %s \n", bufrecv.mtext);
}
//delete the message queue
if (msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl failed");
exit(1);
}
return 0;
}