Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/ipc.h>
  6. #include <sys/msg.h>
  7. #include <errno.h>
  8.  
  9. struct mymsgbuf {
  10. long mtype; /* typ wiadomości */
  11. int request; /* numer żądania danego działania */
  12. int i;
  13. } msg;
  14.  
  15. struct mymsgbuf buf;
  16.  
  17. int open_queue( key_t keyval )
  18. {
  19. int qid;
  20.  
  21. if((qid = msgget( keyval, IPC_CREAT | 0660 )) == -1)
  22. return(-1);
  23.  
  24. return(qid);
  25. }
  26.  
  27. int send_message( int qid, struct mymsgbuf *qbuf )
  28. {
  29. int result, length;
  30.  
  31. /* lenght jest rozmiarem struktury minus sizeof(mtype) */
  32. length = sizeof(struct mymsgbuf) - sizeof(long);
  33.  
  34. if((result = msgsnd( qid, qbuf, length, 0)) == -1)
  35. return(-1);
  36.  
  37. return(result);
  38. }
  39.  
  40. int remove_queue( int qid )
  41. {
  42. if( msgctl( qid, IPC_RMID, 0) == -1)
  43. return(-1);
  44.  
  45. return(0);
  46. }
  47.  
  48. int read_message( int qid, long type, struct mymsgbuf *qbuf )
  49. {
  50. int result, length;
  51.  
  52. /* lenght jest rozmiarem struktury minus sizeof(mtype) */
  53. length = sizeof(struct mymsgbuf) - sizeof(long);
  54.  
  55. if((result = msgrcv( qid, qbuf, length, type, 0)) == -1)
  56. return(-1);
  57.  
  58. return(result);
  59. }
  60.  
  61. int main(void)
  62. {
  63. int a,s,j,d;
  64. int qid;
  65. key_t msgkey;
  66. printf("podaj liczbe procesow");
  67. scanf("%d",&a);
  68. for (j=0;j<a;j++)
  69. {
  70. printf("Proces (PID: %d) \n", getpid());
  71. //scanf("%d","%l","%d",&a,d,&s);
  72. }
  73. printf("podaj wartosc");
  74. scanf("%d",&d);
  75. printf("podaj pid do ktorego chcesz przekazac wartosc");
  76. scanf("%d",&s);
  77. /* tworzymy wartość klucza IPC */
  78. msgkey = ftok(".", 'm');
  79.  
  80. /* otwieramy/tworzymy kolejkę */
  81. if(( qid = open_queue( msgkey)) == -1)
  82. {
  83. perror("Otwieranie_kolejki");
  84. exit(1);
  85. }
  86.  
  87. msg.mtype = d; /* typ wiadomości musi być dodatni */
  88. msg.request = 1;
  89. msg.i = d;/* wysyana liczba */
  90.  
  91.  
  92.  
  93.  
  94.  
  95.  
  96.  
  97. if((send_message( qid, &msg )) == -1)
  98. {
  99. perror("Wysylanie");
  100. exit(1);
  101. }
  102.  
  103. /* Odbieramy */
  104. buf.mtype = d; /* typ wiadomości musi być dodatni */
  105. buf.request = 1;
  106.  
  107. /* Odbieramy wiadomosc */
  108. read_message(qid, buf.mtype, &buf);
  109. printf("Zawartosc: %d\n", buf.i);
  110. remove_queue(qid);
  111.  
  112.  
  113. return 0;
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement