Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED)
- /* jest zdefiniowane w sys/sem.h */
- #else
- union semun
- {
- int val; //value for SETVAL
- struct semid_ds *buf; //buffer for IPC_STAT, IPC_SET
- unsigned short int *array; //array for GETALL, SETALL
- struct seminfo *__buf; //buffer for IPC_INFO
- }ustaw;
- int ptr[5];
- #endif
- #define TRZYMA_WIDELEC 1
- #define CZEKA 2
- #define POSILEK 3
- #define ODPOCZYWA 4
- int main()
- {
- int i=0, end=1, semafor, widelec =0;
- key_t klucz;
- struct sembuf operacja;
- klucz = ftok( ".", 'a');
- semafor = semget( klucz , 5, IPC_CREAT | 0666 );
- ustaw.val = 1;
- semctl(semafor, 1, SETALL, ustaw.val);
- for(i=0; i<5; i++)
- {
- semctl(semafor, i, GETVAL, ustaw);
- printf("%d", ustaw.val);
- }
- for(i=0;i<5;i++)
- {
- ptr[i]=CZEKA;
- }
- for (i=0; i< 5; i++)
- {
- if( fork() == 0)
- {
- while(end==1)
- {
- printf("%d\n", i);
- // if(ptr[i] == CZEKA)
- // {
- semctl(semafor, i, GETVAL, ustaw);
- if(ustaw.val ==1)
- {
- if (semop(semafor, &operacja, 1) == -1)
- {
- fprintf(stderr, "blad blokowania semafora\\n");
- exit(1);
- }
- operacja.sem_num = i;
- operacja.sem_op = -1; //zablokuj
- operacja.sem_flg = 0; //operacja blokujaca
- if (semop(semafor, &operacja, 1) == -1)
- {
- fprintf(stderr, "blad blokowania semafora\\n");
- exit(1);
- }
- // ptr[i] == TRZYMA_WIDELEC;
- printf ("mi siÄ udalo\n");
- }
- else
- {
- printf("mi sie nie udlo\n");
- // sleep(2);
- }
- //sprawdz czy moĹźesz zabrac widelec
- //nr i
- //jak nie to czeka
- // }
- // else if(ptr[i] == TRZYMA_WIDELEC)
- // {
- //sprawdz czy moĹźesz zabrac widelec i+1
- //jak nie to poczekaj, sprawdz ponownie
- //jak nie to czekaj od nowa
- // }
- // else if(ptr[i] == POSILEK)
- // {
- //poczekaj na zjedzenie
- //odkladaj widelce
- //idz spac
- // }
- // else
- // {
- //pospij
- //przejdz do czekaj
- // }
- // operacja.sem_num = i;
- // operacja.sem_op = -1; //zablokuj
- // operacja.sem_flg = 0; //operacja blokujaca
- // // semop(semafor, &opercaja,)
- // sleep(1);
- }
- }
- }
- while(end ==1)
- {
- for(i=0; i<5; i++)
- printf("Filozof nr %d jest w stanie %d\n", i, ptr[i]);
- sleep(1);
- }
- return 1;
- }
Add Comment
Please, Sign In to add comment