Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <unistd.h>
- #include <signal.h>
- using namespace std;
- int Id;
- int n;
- struct tshared {
- int TRAZIM[10];
- int BROJ[10];
- };
- tshared* share;
- int
- max (int BROJ[])
- {
- int max = BROJ[0];
- for (int i = 1; i < n; i++) {
- if (BROJ[i] > max) {
- max = BROJ[i];
- }
- }
- return max;
- }
- void
- udi_u_kriticni_odsjecak (int i, tshared* share)
- {
- share->TRAZIM[i] = 1;
- share->BROJ[i] = max(share->BROJ) + 1;
- share->TRAZIM[i] = 0;
- for (int j = 0; j < n; j++) { // do n-1 je zapravo <= n-1, to jest <n
- while (share->TRAZIM[j] != 0) { // <> znaci != u pseudokodu
- // ne ispisuj nist dok piste nista, to je radno cekanje
- }
- while (share->BROJ[j] != 0
- && (share->BROJ[j] < share->BROJ[i] || (share->BROJ[j] == share->BROJ[i] && j < i))) {
- }
- }
- }
- void
- izadi_iz_kriticnog_odsjecka (int i, tshared* share) {
- share->BROJ[i] = 0;
- }
- void
- proc (int i, tshared* share)
- {
- for (int k = 1; k <= 5; k++) {
- udi_u_kriticni_odsjecak (i, share);
- for (int m = 1; m <= 5; m++) {
- cout << endl << "Proces: " << i+1 << ", K.O. br: " << k << " " << "("
- << m << "/5)" << endl;
- sleep(1);
- }
- izadi_iz_kriticnog_odsjecka (i, share);
- }
- }
- void
- brisi (int sig)
- {
- shmdt (share->TRAZIM);
- shmdt (share->BROJ);
- shmctl (Id, IPC_RMID, NULL);
- exit (0);
- }
- int
- main () {
- Id = shmget (IPC_PRIVATE, sizeof (int) * 100, 0666);
- if (Id == -1) {
- exit (1);
- }
- sigset (SIGINT, brisi);
- cout<<"int *)N: "; cin>>n;
- share = (tshared*)shmat (Id, NULL, 0);
- for(int i=0;i<n;i++) {
- switch(fork()) {
- case 0: {
- proc(i,share);
- exit(0);
- break;
- }
- default: {
- break;
- }
- }
- }
- for(int i=0;i<n;i++){
- wait(NULL);
- }
- brisi (0);
- sleep(10);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement