Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Napisz dwa programy, które b ę d ą komunikować się poprzez pamięć dzielon ą .
- W trakcie dzia ł ania programów (np. po dwóch wys ł anych i odebranych komunikatach) niech program b ę d ą cy w ł a ś cicielem pami ę ci zamieni jej prawa dost ę pu, tak, aby tylko on móg ł z niej korzysta ć . Poka ż co si ę wtedy stanie.
- */
- // Program drugi
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/ipc.h>
- #include <sys/types.h>
- #include <sys/sem.h>
- #include <sys/shm.h>
- #include <unistd.h>
- #define FTOK_PATH "/tmp"
- #define FTOK_ID 0x712
- void error_handler(const char *msg)
- {
- perror(msg);
- exit(EXIT_FAILURE);
- }
- void mux_up(int mux)
- {
- struct sembuf up_operation = {0, 1, 0};
- if(semop(mux, &up_operation, 1) == -1)
- error_handler("semop_up");
- }
- void mux_down(int mux)
- {
- struct sembuf down_operation = {0, -1, 0};
- if(semop(mux, &down_operation, 1) == -1)
- error_handler("semop_down");
- }
- int main(void)
- {
- int shmid, mux;
- int *shared_memory;
- key_t key;
- int buffer;
- if((key = ftok(FTOK_PATH, FTOK_ID)) == -1)
- error_handler("ftok");
- if((mux = semget(key, 1, 0660 | IPC_CREAT)) == -1)
- error_handler("semget");
- if((shmid = shmget(key, SHMLBA, 0660 | IPC_CREAT)) == -1)
- error_handler("semctl");
- for(int i = 0; i <= 5; i++){
- mux_down(mux);
- if((shared_memory = (int *)shmat(shmid, NULL, 0)) == (void *)-1)
- error_handler("shmat");
- buffer = shared_memory[i];
- printf("Odczytano z pamieci dzielonej liczbe: %d\n", buffer);
- }
- if(shmdt(shared_memory) == -1)
- error_handler("shmdt");
- if(shmctl(shmid, IPC_RMID, NULL) == -1)
- error_handler("shmctl");
- if(semctl(mux, 0, IPC_RMID, NULL) == -1)
- error_handler("semctl");
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment