Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/ipc.h>
  5. #include <sys/msg.h>
  6. #include <sys/shm.h>
  7. #include <sys/wait.h>
  8. #include <sys/signal.h>
  9.  
  10. #define LICZBA_FILOZOFOW 5 //liczba filozofow
  11. #define IL 3 //ilosc papu filozofow (ile razy jedza)
  12. struct bufor
  13. {
  14. long mtype;
  15. int mvalue;
  16. };
  17.  
  18. void koniec(int sig);
  19.  
  20. int msgID,shmID;
  21. int main(int argc,char *argv[])
  22. {
  23. key_t kluczm, klucz;
  24. int *pam;
  25. char bufor[3];
  26. int i;
  27. struct bufor komunikat;
  28. struct sigaction act;
  29. if ((kluczm = ftok(".", 'A')) == -1)
  30. {
  31. printf("MAIN: Blad kluczs\n");
  32. exit(1);
  33. }
  34.  
  35. shmID=shmget(kluczm, LICZBA_FILOZOFOW * sizeof(int), IPC_CREAT | IPC_EXCL | 0666);
  36. if(shmID==-1){
  37. printf("Blad shmget");
  38. exit(1);
  39. }
  40.  
  41. if ((klucz = ftok(".", 'B')) == -1)
  42. {
  43. printf("Blad ftok (main)\n");
  44. exit(1);
  45. }
  46. msgID = msgget(klucz, IPC_CREAT | IPC_EXCL | 0666);
  47. if (msgID == -1)
  48. {
  49. printf("blad kolejki komunikatow\n");
  50. exit(1);
  51. }
  52.  
  53. pam=(int*)shmat(shmID,NULL,0);
  54.  
  55. if(*pam==-1){
  56. printf("Problem z przydzieleniem adresu.\n");
  57. exit(1);
  58. }
  59.  
  60. for (i = 0; i < LICZBA_FILOZOFOW; i++)
  61. pam[i]=0;
  62.  
  63.  
  64. for (i = 0; i < LICZBA_FILOZOFOW; i++)
  65. {
  66. komunikat.mtype = i + 1;//nie mog byc zera w kk, bo potem wystapi problem przy odbiorze
  67. if (msgsnd(msgID, &komunikat, sizeof(komunikat.mvalue), 0) == -1) //wyslanie komunikatu
  68. {
  69. printf("blad wyslania kom. pustego\n");
  70. exit(1);
  71. };
  72. printf("wyslany pusty komunikat %d\n", i);
  73. }
  74.  
  75. for (i = 0; i < IL*LICZBA_FILOZOFOW; i++){
  76. switch (fork())
  77. {
  78. case -1:
  79. perror("MAIN: Blad fork");
  80. exit(2);
  81. case 0:
  82. sprintf(bufor,"%d",i%5);
  83. execl("./filozof", "filozof",bufor, NULL);
  84. }
  85. }
  86.  
  87. act.sa_handler=koniec;
  88. sigemptyset(&act.sa_mask);
  89. act.sa_flags=0;
  90. sigaction(SIGINT,&act,0);
  91.  
  92. for (i = 0; i < IL*LICZBA_FILOZOFOW; i++)//czekanie na zakonczenie watkow
  93. wait(NULL);
  94.  
  95. msgctl(msgID, IPC_RMID, NULL);
  96. shmctl(shmID, IPC_RMID, NULL);
  97. printf("MAIN: Koniec programu\n");
  98. }
  99.  
  100. void koniec(int sig)
  101. {
  102. msgctl(msgID,IPC_RMID,NULL);
  103. shmctl(shmID,IPC_RMID, NULL);
  104. printf("MAIN - funkcja koniec sygnal %d: Koniec.\n",sig);
  105. exit(1);
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement