Advertisement
Kacper_Michalak

Zad_4a

Nov 11th, 2023 (edited)
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. // Program wysyłający komunikaty 0 losowo wybranym typie
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #include <sys/types.h>
  6. #include <sys/ipc.h>
  7. #include <sys/msg.h>
  8.  
  9. #define MSG_KEY 1234 // klucz kolejki komunikatów
  10. #define MSG_NUM 5 // liczba komunikatów do wysłania
  11.  
  12. // struktura komunikatu 0
  13. struct msgbuf {
  14. long mtype; // typ komunikatu
  15. char mtext[1]; // treść komunikatu (pusta)
  16. };
  17.  
  18. int main() {
  19. int msgid; // identyfikator kolejki komunikatów
  20. struct msgbuf msg; // komunikat do wysłania
  21. srand(time(NULL)); // inicjalizacja generatora liczb losowych
  22. // tworzenie lub otwieranie kolejki komunikatów
  23. msgid = msgget(MSG_KEY, IPC_CREAT | 0666);
  24. if (msgid == -1) {
  25. perror("msgget");
  26. exit(1);
  27. }
  28. // wysyłanie losowych komunikatów 0
  29. for (int i = 0; i < MSG_NUM; i++) {
  30. msg.mtype = rand() % 5 + 1; // losowy typ z przedziału [1,5]
  31. msg.mtext[0] = '\0'; // pusta treść
  32. // wysyłanie komunikatu do kolejki
  33. if (msgsnd(msgid, &msg, 0, 0) == -1) {
  34. perror("msgsnd");
  35. exit(2);
  36. }
  37. printf("Wysłano komunikat %d typu %ld\n",i+1, msg.mtype);
  38. }
  39. return 0;
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement