Advertisement
Guest User

Untitled

a guest
May 20th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <signal.h>
  3. #include <termios.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <string.h>
  7. #include <unistd.h>
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <sys/ipc.h>
  11. #include <sys/msg.h>
  12.  
  13.  
  14. #define MSGSIZE 100
  15. #define STRUCTMSGSIZE (MSGSIZE + sizeof(pid_t))
  16. #define ERRCODE -1
  17. #define NO_FLAGS 0
  18. #define MSGJOINQ 1
  19. #define MSGLEAVEQ 2
  20. #define MSG_TYPE_DATA 3
  21. #define MSG_ALL_TYPES 0
  22. #define QUEUE_RIGHTS 0600
  23. #define PROJECT_PREFIX 97
  24. #define COUNT_MESSAGES 10
  25. #define START_CHAR 32
  26. #define END_CHAR 127
  27. #define SLEEP_TIME 1
  28.  
  29. struct message {
  30.   long mtype;
  31.   pid_t pid;
  32.   char mtext[MSGSIZE];
  33. };
  34.  
  35.  
  36. int qclose(int queue) {
  37.   if(msgctl(queue,IPC_RMID,NULL) == ERRCODE) {
  38.     perror("msgctl");
  39.     return EXIT_FAILURE;
  40.   }
  41.  
  42.   return EXIT_SUCCESS;
  43. }
  44.  
  45. int qrecv(int queue) {
  46.   struct message buf;
  47.   int count = 0;
  48.   do {
  49.     ssize_t length;
  50.     if((length = msgrcv(queue, &buf, STRUCTMSGSIZE, MSG_ALL_TYPES, NO_FLAGS)) == ERRCODE) {
  51.       perror("msgrcv");
  52.       return EXIT_FAILURE;
  53.     }
  54.  
  55.     switch(buf.mtype) {
  56.       case MSGJOINQ:
  57.         ++count;
  58.         printf("new sender %d\n", buf.pid);
  59.         break;
  60.  
  61.       case MSGLEAVEQ:
  62.         --count;
  63.         printf("del sender %d\n", buf.pid);
  64.         break;
  65.  
  66.       default:
  67.         printf("process %d: %s\n", buf.pid, buf.mtext);
  68.     }
  69.   } while (count > 0);
  70.  
  71.   return EXIT_SUCCESS;
  72. }
  73.  
  74. int main() {
  75.   key_t queueKey = ftok("master.c", PROJECT_PREFIX);
  76.   if(queueKey == ERRCODE) {
  77.     perror("ftok");
  78.     return EXIT_FAILURE;
  79.   }
  80.  
  81.   int queue;
  82.   queue = msgget(queueKey, IPC_CREAT | QUEUE_RIGHTS);
  83.   if(queue == ERRCODE) {
  84.     perror("msgget");
  85.     return EXIT_FAILURE;
  86.   }
  87.  
  88.   printf("Queue was created\n");
  89.  
  90.   if(qrecv(queue) != EXIT_SUCCESS) {
  91.     qclose(queue);
  92.     return EXIT_FAILURE;
  93.   }
  94.  
  95.   if(qclose(queue) != EXIT_SUCCESS) {
  96.     return EXIT_FAILURE;
  97.   }
  98.  
  99.   return EXIT_SUCCESS;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement