Advertisement
Kacper_Michalak

Zad_4b

Nov 11th, 2023 (edited)
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. // Program odbierający komunikaty 0 w porządku malejącym lub rosnącym
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/ipc.h>
  6. #include <sys/msg.h>
  7.  
  8. #define MSG_KEY 1234 // klucz kolejki komunikatów
  9.  
  10. // struktura komunikatu 0
  11. struct msgbuf {
  12. long mtype; // typ komunikatu
  13. char mtext[1]; // treść komunikatu (pusta)
  14. };
  15.  
  16. int main() {
  17. int msgid; // identyfikator kolejki komunikatów
  18. struct msgbuf msg; // komunikat do odebrania
  19. char order; // wybór porządku odbierania
  20. long mtype; // typ komunikatu do odebrania
  21. // otwieranie kolejki komunikatów
  22. msgid = msgget(MSG_KEY, 0);
  23. if (msgid == -1) {
  24. perror("msgget");
  25. exit(1);
  26. }
  27. // pytanie użytkownika o porządek odbierania
  28. printf("W jakim porządku chcesz odbierać komunikaty 0? (r - rosnąco, m - malejąco)\n");
  29. scanf("%c", &order);
  30. if (order == 'r') {
  31. mtype = 1; // odbieranie od typu 1
  32. } else if (order == 'm') {
  33. mtype = 5; // odbieranie od typu 5
  34. } else {
  35. printf("Nieprawidłowy wybór\n");
  36. exit(2);
  37. }
  38. // odbieranie komunikatów 0 w wybranym porządku
  39. while (1) {
  40. // odbieranie komunikatu z kolejki
  41. if (msgrcv(msgid, &msg, 0, mtype, IPC_NOWAIT) == -1) {
  42. // jeśli nie ma komunikatu danego typu, zmienić typ
  43. if (order == 'r') {
  44. mtype++; // zwiększyć typ
  45. } else {
  46. mtype--; // zmniejszyć typ
  47. }
  48. // jeśli przekroczono zakres typów, zakończyć program
  49. if (mtype < 1 || mtype > 5) {
  50. break;
  51. }
  52. } else {
  53. // jeśli odebrano komunikat, wyświetlić jego typ
  54. printf("Odebrano komunikat typu %ld\n", msg.mtype);
  55. }
  56. }
  57. return 0;
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement