1 int msgid; /* Message queue identifier */
2 int main(int argc, char *argv[])
4 /* Variables definition */
6 char **fortune; /* array of fortune message string */
7 char *fortunefilename = "/usr/share/games/fortunes/linux"; /* file name */
8 struct msgbuf_read { /* message struct to read request from clients */
9 long mtype; /* message type, must be 1 */
10 long pid; /* message data, must be the pid of the client */
12 struct msgbuf_write { /* message struct to write result to clients */
13 long mtype; /* message type, will be the pid of the client*/
14 char mtext[MSGMAX]; /* message data, will be the fortune */
16 key_t key; /* Message queue key */
17 int size; /* message size */
19 Signal(SIGTERM, HandSIGTERM); /* set handlers for termination */
20 Signal(SIGINT, HandSIGTERM);
21 Signal(SIGQUIT, HandSIGTERM);
22 if (n==0) usage(); /* if no pool depth exit printing usage info */
23 i = FortuneParse(fortunefilename, fortune, n); /* parse phrases */
24 /* Create the queue */
25 key = ftok("./MQFortuneServer.c", 1);
26 msgid = msgget(key, IPC_CREAT|0666);
28 perror("Cannot create message queue");
31 /* Main body: loop over requests */
34 msgrcv(msgid, &msg_read, sizeof(int), 1, MSG_NOERROR);
35 n = random() % i; /* select random value */
36 strncpy(msg_write.mtext, fortune[n], MSGMAX);
37 size = min(strlen(fortune[n])+1, MSGMAX);
38 msg_write.mtype=msg_read.pid; /* use request pid as type */
39 msgsnd(msgid, &msg_write, size, 0);
43 * Signal Handler to manage termination
45 void HandSIGTERM(int signo) {
46 msgctl(msgid, IPC_RMID, NULL); /* remove message queue */