Tobiahao

S01_LAB03_01

Nov 14th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.20 KB | None | 0 0
  1. /*
  2. Napisz program, który utworzy prywatną kolejkę i będzie przesyłał nią
  3. komunikaty.
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <sys/types.h>
  9. #include <sys/ipc.h>
  10. #include <sys/msg.h>
  11. #include <string.h>
  12.  
  13. #define MESSAGE_TO_SEND "Wiadomosc..."
  14. #define BUFFER_SIZE 128
  15.  
  16. struct msgbuf {
  17.     long mtype;
  18.     char mtext[BUFFER_SIZE];
  19. };
  20.  
  21. void send_message(int id)
  22. {
  23.     struct msgbuf send_buffer;
  24.  
  25.     send_buffer.mtype = 1;
  26.     memset(send_buffer.mtext, '\0', BUFFER_SIZE-1);
  27.     strncpy(send_buffer.mtext, MESSAGE_TO_SEND, BUFFER_SIZE-1);
  28.    
  29.     if(msgsnd(id, &send_buffer, strlen(send_buffer.mtext), 0) == -1){
  30.         perror("msgsnd");
  31.         exit(EXIT_FAILURE);
  32.     }
  33. }
  34.  
  35. void recv_message(int id)
  36. {
  37.     struct msgbuf recv_buffer;
  38.  
  39.     if(msgrcv(id, &recv_buffer, sizeof(recv_buffer.mtext), 1, 0) == -1){
  40.         perror("msgrecv");
  41.         exit(EXIT_FAILURE);
  42.     }
  43.  
  44.     printf("Przeslana wiadomosc: %s\n", recv_buffer.mtext);
  45. }
  46.  
  47. int main(void)
  48. {
  49.     int id;
  50.     if((id = msgget(IPC_PRIVATE, 0600 | IPC_CREAT)) == -1){
  51.         perror("msgget");
  52.         return EXIT_FAILURE;
  53.     }
  54.  
  55.     send_message(id);
  56.     recv_message(id);
  57.  
  58.     if(msgctl(id, IPC_RMID, 0) == -1){
  59.         perror("msgctl");
  60.         return EXIT_FAILURE;
  61.     }
  62.  
  63.     return EXIT_SUCCESS;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment