Aggiornamenti + alcune sockopt di IP
[gapil.git] / listati / MQFortuneServer.c
1 int msgid;          /* Message queue identifier */
2 int main(int argc, char *argv[])
3 {
4 /* Variables definition */
5     int i, n = 0;
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 */
11     } msg_read;
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 */
15     } msg_write;
16     key_t key;            /* Message queue key */
17     int size;             /* message size */
18     ...
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);
27     if (msgid < 0) {
28         perror("Cannot create message queue");
29         exit(1);
30     }
31     /* Main body: loop over requests */
32     daemon(0, 0);
33     while (1) {
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);
40     }
41 }
42 /*
43  * Signal Handler to manage termination
44  */
45 void HandSIGTERM(int signo) {
46     msgctl(msgid, IPC_RMID, NULL);    /* remove message queue */
47     exit(0);
48 }