Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Program wysyłający komunikaty 0 losowo wybranym typie
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #define MSG_KEY 1234 // klucz kolejki komunikatów
- #define MSG_NUM 5 // liczba komunikatów do wysłania
- // struktura komunikatu 0
- struct msgbuf {
- long mtype; // typ komunikatu
- char mtext[1]; // treść komunikatu (pusta)
- };
- int main() {
- int msgid; // identyfikator kolejki komunikatów
- struct msgbuf msg; // komunikat do wysłania
- srand(time(NULL)); // inicjalizacja generatora liczb losowych
- // tworzenie lub otwieranie kolejki komunikatów
- msgid = msgget(MSG_KEY, IPC_CREAT | 0666);
- if (msgid == -1) {
- perror("msgget");
- exit(1);
- }
- // wysyłanie losowych komunikatów 0
- for (int i = 0; i < MSG_NUM; i++) {
- msg.mtype = rand() % 5 + 1; // losowy typ z przedziału [1,5]
- msg.mtext[0] = '\0'; // pusta treść
- // wysyłanie komunikatu do kolejki
- if (msgsnd(msgid, &msg, 0, 0) == -1) {
- perror("msgsnd");
- exit(2);
- }
- printf("Wysłano komunikat %d typu %ld\n",i+1, msg.mtype);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement