Haifisch7734

Untitled

Nov 12th, 2014
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1.  #include <sys/types.h>
  2. #include <sys/ipc.h>
  3. #include <sys/shm.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <sys/sem.h>
  7. #include <time.h>
  8. #include <unistd.h>
  9. #include <signal.h>
  10.  
  11. int id_shmget,semid=-1;
  12. int*adres;
  13. struct shmid_ds *buf;
  14.  
  15. void koniec()
  16. {
  17.     printf("Usunieto semafor i pamiec dzielona. Koniec programu\n.");
  18.     semctl(semid,0,IPC_RMID,0);
  19.     shmdt(adres);
  20.     shmctl(id_shmget,IPC_RMID,buf);
  21.     exit(0);
  22. }
  23. static struct sembuf op_lock[1]={
  24. {1,-1,0}
  25. };
  26.  
  27. static struct sembuf op_unlock[1]={
  28. {0,1,0}
  29. };
  30.  
  31. void blokuj(int semid)
  32. {
  33. if(semop(semid,&op_lock[0],1)<0)
  34.         perror("blad blokowania semafora");
  35. }
  36.  
  37. void odblokuj(int semid)
  38. {
  39. if(semop(semid,&op_unlock[0],1)<0)
  40.         perror("blad odlokowania semafora");
  41. }
  42.  
  43. int main()
  44. {
  45.     signal(SIGINT,koniec);
  46.     srand(time(NULL));
  47.  
  48.     id_shmget=shmget(1337,sizeof(int), IPC_CREAT | IPC_EXCL |0666);
  49. if(id_shmget==-1)
  50. {
  51.         exit(0);
  52. }
  53. else printf ("Utworzono segment pamieci wspolnej \n");
  54.  
  55. if((semid = semget(ftok("serwer.c",0),2, IPC_CREAT |0666))<0)
  56.         perror("Blad tworzenia semafora");
  57.  
  58.     adres=shmat(id_shmget,0,0);
  59. int czas;
  60. int liczba=1;
  61. while(1)
  62. {
  63.         blokuj(semid);
  64.         czas=rand()%1000000;
  65.         usleep(czas);
  66.     (*adres)=liczba;
  67.     printf("%d\n",*adres);
  68.         odblokuj(semid);
  69.         liczba++;
  70. }
  71. return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment