Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/sem.h>
- #include <sys/shm.h>
- #include <string.h>
- #include <unistd.h>
- #include <wait.h>
- #include <sys/ipc.h>
- void up_and_wait(int mux)
- {
- struct sembuf up = {0, 1, 0};
- struct sembuf wait = {0, 0, 0};
- if(semop(mux, &up, 1) < 0)
- perror("semop up");
- if(semop(mux, &wait, 1) < 0)
- perror("semop wait");
- }
- void down (int mux)
- {
- struct sembuf down = {0, -1, 0};
- if(semop(mux, &down, 1) < 0)
- perror("semop down");
- }
- void writer(int mux, int shmid)
- {
- char *str = shmat(shmid, NULL, 0);
- if(str == (void*)-1)
- perror("writer shmat");
- down(mux);
- strncpy(str, "Systemy Operacyjne 1", 50);
- if(shmdt(str) < 0)
- perror("writer strdt");
- exit(0);
- }
- void reader(int mux, int shmid)
- {
- char *str = shmat(shmid, NULL, 0);
- if(str == (void*)-1)
- perror("reader shmat");
- up_and_wait(mux);
- printf("Odczytana wiadomosc: %s\n", str);
- if(shmdt(str) < 0)
- perror("reader strdt");
- if(wait(NULL) < 0)
- perror("wait");
- }
- int main(void)
- {
- int mux = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT | IPC_EXCL);
- if(mux < 0)
- perror("semget");
- int shmid = shmget(IPC_PRIVATE, 4096, 0600 | IPC_CREAT | IPC_EXCL);
- if(shmid < 0)
- perror("shmget");
- int pid = fork();
- if(pid < 0)
- perror("fork");
- if(pid == 0)
- writer(mux, shmid);
- else
- reader(mux, shmid);
- if(shmctl(shmid, IPC_RMID, NULL) < 0)
- perror("shmctl");
- if(semctl(mux, 0, IPC_RMID, NULL) < 0)
- perror("semctl");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement