Advertisement
d1cor

mq2_b.c

Sep 27th, 2017
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.23 KB | None | 0 0
  1. /*
  2.  * client.c: Client 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. #include <unistd.h>
  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.     char client_queue_name [64];
  25.     mqd_t qd_server, qd_client;   // queue descriptors
  26.  
  27.  
  28.     // create the client queue for receiving messages from server
  29.     sprintf (client_queue_name, "/sp-example-client-%d", getpid ());
  30.  
  31.     struct mq_attr attr;
  32.  
  33.     attr.mq_flags = 0;
  34.     attr.mq_maxmsg = MAX_MESSAGES;
  35.     attr.mq_msgsize = MAX_MSG_SIZE;
  36.     attr.mq_curmsgs = 0;
  37.  
  38.     if ((qd_client = mq_open (client_queue_name, O_RDONLY | O_CREAT, QUEUE_PERMISSIONS, &attr)) == -1) {
  39.         perror ("Client: mq_open (client)");
  40.         exit (1);
  41.     }
  42.  
  43.     if ((qd_server = mq_open (SERVER_QUEUE_NAME, O_WRONLY)) == -1) {
  44.         perror ("Client: mq_open (server)");
  45.         exit (1);
  46.     }
  47.  
  48.     char in_buffer [MSG_BUFFER_SIZE];
  49.  
  50.     printf ("Ask for a token (Press < ENTER >): ");
  51.  
  52.     char temp_buf [10];
  53.  
  54.     while (fgets (temp_buf, 2, stdin)) {
  55.  
  56.         // send message to server
  57.         if (mq_send (qd_server, client_queue_name, strlen (client_queue_name), 0) == -1) {
  58.             perror ("Client: Not able to send message to server");
  59.             continue;
  60.         }
  61.  
  62.         // receive response from server
  63.  
  64.         if (mq_receive (qd_client, in_buffer, MSG_BUFFER_SIZE, NULL) == -1) {
  65.             perror ("Client: mq_receive");
  66.             exit (1);
  67.         }
  68.         // display token received from server
  69.         printf ("Client: Token received from server: %s\n\n", in_buffer);
  70.  
  71.         printf ("Ask for a token (Press ): ");
  72.     }
  73.  
  74.  
  75.     if (mq_close (qd_client) == -1) {
  76.         perror ("Client: mq_close");
  77.         exit (1);
  78.     }
  79.  
  80.     if (mq_unlink (client_queue_name) == -1) {
  81.         perror ("Client: mq_unlink");
  82.         exit (1);
  83.     }
  84.     printf ("Client: bye\n");
  85.  
  86.     exit (0);
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement