Advertisement
d1cor

mq2_a.c

Sep 27th, 2017
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.87 KB | None | 0 0
  1. /*
  2.  * server.c: Server program
  3.  *           to demonstrate interprocess commnuication
  4.  *           with POSIX message queues
  5.  */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <sys/types.h>
  11.  
  12. #include <fcntl.h>
  13. #include <sys/stat.h>
  14. #include <mqueue.h>
  15.  
  16. #define SERVER_QUEUE_NAME   "/sp-example-server"
  17. #define QUEUE_PERMISSIONS 0660
  18. #define MAX_MESSAGES 10
  19. #define MAX_MSG_SIZE 256
  20. #define MSG_BUFFER_SIZE MAX_MSG_SIZE + 10
  21.  
  22. int main (int argc, char **argv)
  23. {
  24.     mqd_t qd_server, qd_client;   // queue descriptors
  25.     long token_number = 1; // next token to be given to client
  26.  
  27.     printf ("Server: Hello, World!\n");
  28.  
  29.     struct mq_attr attr;
  30.  
  31.     attr.mq_flags = 0;
  32.     attr.mq_maxmsg = MAX_MESSAGES;
  33.     attr.mq_msgsize = MAX_MSG_SIZE;
  34.     attr.mq_curmsgs = 0;
  35.  
  36.     if ((qd_server = mq_open (SERVER_QUEUE_NAME, O_RDONLY | O_CREAT, QUEUE_PERMISSIONS, &attr)) == -1) {
  37.         perror ("Server: mq_open (server)");
  38.         exit (1);
  39.     }
  40.     char in_buffer [MSG_BUFFER_SIZE];
  41.     char out_buffer [MSG_BUFFER_SIZE];
  42.  
  43.     while (1) {
  44.         // get the oldest message with highest priority
  45.         if (mq_receive (qd_server, in_buffer, MSG_BUFFER_SIZE, NULL) == -1) {
  46.             perror ("Server: mq_receive");
  47.             exit (1);
  48.         }
  49.  
  50.         printf ("Server: message received: %s\n", in_buffer);
  51.  
  52.         // send reply message to client
  53.  
  54.         if ((qd_client = mq_open (in_buffer, O_WRONLY)) == 1) {
  55.             perror ("Server: Not able to open client queue");
  56.             continue;
  57.         }
  58.  
  59.         sprintf (out_buffer, "%ld", token_number);
  60.  
  61.         if (mq_send (qd_client, out_buffer, strlen (out_buffer), 0) == -1) {
  62.             perror ("Server: Not able to send message to client");
  63.             continue;
  64.         }
  65.  
  66.         printf ("Server: response sent to client.\n");
  67.         token_number++;
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement