Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Zademonstruj synchronizację operacji zapisu i odczytu dla łącza nazwa- nego, przy pomocy semaforów.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/ipc.h>
- #include <sys/types.h>
- #include <sys/sem.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <sys/wait.h>
- #define FIFO_DIR "fifo"
- #define MESSAGE "Jakas wiadomosc!"
- void sem_up(int semid)
- {
- struct sembuf up_operation = {0, 1, 0};
- if(semop(semid, &up_operation, 1) == -1){
- perror("up_semop");
- exit(EXIT_FAILURE);
- }
- }
- void sem_down(int semid)
- {
- struct sembuf down_operation = {0, -1, 0};
- if(semop(semid, &down_operation, 1) == -1){
- perror("down_semop");
- exit(EXIT_FAILURE);
- }
- }
- int main(void)
- {
- int fifofd, semid;
- pid_t pid;
- if(mkfifo(FIFO_DIR, 0775) == -1){
- perror("mkfifo");
- return EXIT_FAILURE;
- }
- if((semid = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT | IPC_EXCL)) == -1){
- perror("semget");
- return EXIT_FAILURE;
- }
- if(semctl(semid, 0, SETVAL, 1) == -1){
- perror("setval_semctl");
- return EXIT_FAILURE;
- }
- if((fifofd = open(FIFO_DIR, O_RDWR)) == -1){
- perror("open");
- return EXIT_FAILURE;
- }
- pid = fork();
- if(pid == -1){
- perror("fork");
- return EXIT_FAILURE;
- }
- else if(pid == 0){
- sem_down(semid);
- for(int i = 0; i < 10; i++){
- if(write(fifofd, &i, sizeof(int)) == -1){
- perror("write");
- return EXIT_FAILURE;
- }
- }
- if(close(fifofd) == -1){
- perror("child_close");
- return EXIT_FAILURE;
- }
- sem_up(semid);
- }
- else{
- for(int i = 0; i < 10; i++){
- int buffer;
- if(read(fifofd, &buffer, sizeof(int)) == -1){
- perror("read");
- return EXIT_FAILURE;
- }
- printf("%d ", buffer);
- }
- printf("\n");
- if(close(fifofd) == -1){
- perror("parent_close");
- return EXIT_FAILURE;
- }
- if(semctl(semid, 0, IPC_RMID) == -1){
- perror("semctl");
- return EXIT_FAILURE;
- }
- if(unlink(FIFO_DIR) == -1){
- perror("unlink");
- return EXIT_FAILURE;
- }
- }
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment