Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- klient--------------------------------
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <sys/sem.h>
- #include <signal.h>
- #include <time.h>
- // operacja blokowania 1 semafora
- static struct sembuf op_lock1[1] =
- {
- {0, -1, 0}
- };
- // drugi sem block
- static struct sembuf op_unlock2[1] =
- {
- {1, 1, 0}
- };
- // fun wykoanie struktury
- void lock_sem1(int semid)
- {
- if (semop(semid, &op_lock1[0], 1)<0)
- perror("Semaphor1 lock error");
- }
- // anlokwanie sem
- void unlock_sem2(int semid)
- {
- if (semop(semid, &op_unlock2[0], 1) < 0)
- perror("Semaphor2 unlock error");
- }
- int *shmp;
- int semid;
- int shmid;
- int main(){
- int number;
- int i;
- int time_to_wait;
- srand(time(0));
- // uzykanie dostepu pamieci dzielonej
- int shmid= shmget(ftok("/tmp/",123), sizeof(int),0666 | IPC_EXCL);
- if (shmid==-1){
- perror("Shmget error");
- exit(0);
- }
- // przylacza pamiec dzielona gdzie ma byc przylaczona wsk
- shmp = shmat(shmid,0, 0);
- if (shmp==NULL){
- perror("Shmat error");
- exit(0);
- }
- // uzykanie dostepu semafora tworzy 2
- semid = semget(ftok("/tmp/",123), 2, 0666 | IPC_EXCL);
- if (semid < 0){
- perror("Semget error");
- }
- for(i=0;i<10;i++){
- // lokuje pierwszy sem
- lock_sem1(semid);
- number=*shmp;//
- unlock_sem2(semid);//anlokuje sem 2
- printf("Number: %d\n",number);
- time_to_wait=rand()%1000001;
- usleep(time_to_wait);
- }
- shmdt(shmp);// odlaczenie pamiec dzielonej
- return 0;
- }
- -------------------------------------serwer-----------------------------
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <sys/sem.h>
- #include <signal.h>
- #include <time.h>
- // struktoura odblokwanie sam 1
- static struct sembuf op_unlock1[1] =
- {
- {0, 1, 0}
- };
- static struct sembuf op_lock2[1] =
- {
- {1, -1, 0}
- };
- // zeby na poczatku odblokowac
- static struct sembuf op_unlock2[1] =
- {
- {1, 1, 0}
- };
- // fun do odblokowania
- void unlock_sem1(int semid)
- {
- if (semop(semid, &op_unlock1[0], 1) < 0)
- perror("Semaphor1 unlock error");
- }
- void lock_sem2(int semid)
- {
- if (semop(semid, &op_lock2[0], 1)<0)
- perror("Semaphor2 lock error");
- }
- void unlock_sem2(int semid)
- {
- if (semop(semid, &op_unlock2[0], 1) < 0)
- perror("Semaphor2 unlock error");
- }
- int *shmp;
- int semid;
- int shmid;
- // funkcja oblsugi syhnalu ctrl c
- void signal_function(int nr_sig)
- {
- if(shmdt(shmp)<0)// odlaczana pamiec
- perror("Shmdt error");
- if(semctl(semid,0,IPC_RMID,0)<0)//usuwanie sem
- perror("Semctl error");
- if(shmctl(shmid,IPC_RMID,NULL)<0) // usuwanie pamiec dzielonej
- perror("Shmctl error");
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement