Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Напсиать программу, реализующую задачу "Производство потребление"
- * по алгоритму Э. Дейкстры с тремя семафорами: двумя считающими и ъодним бинарным.
- *
- * В программе надо обесмпечить случайные задержки выполнения созданных
- * процессов.
- *
- * В программе для взаимодействия производиттелей и
- * потребителей буфер создается в разделямом сгементе.
- *
- * Обратите внимание на то, чтобы не рабтоать с одиночной перемнной,
- * а работать именно с буфером, состоящим из N ячеек, по алгоритму.
- *
- * Производитлеи в ячейки буфера записывают буквы алфамита по порядку.
- *
- * Потребители считывают символы из
- * считывания буквы из ячейки следуюзий потребитель может взять букву из следующей ячейки
- */
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #include <sys/stat.h>
- #include <sys/shm.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- const int MY_FLAG = IPC_CREAT | S_URWXU | S_IRWXG | S_IRWXO;
- const int num = 10;
- const int count = 15;
- int *buf;
- int *pos;
- #define PROD (0)
- #define CONS (1)
- #define BIN (2)
- struct sembuf start_produce[2] = {{PROD, -1, 0} ,{BIN, -1, 0}};
- struct sembuf stop_produce[2] = {{PROD, 1, 0} ,{BIN, 1, 0}};
- struct sembuf start_consume[2] = {{CONS, -1,0} ,{BIN, -1, 0}};
- struct sembuf stop_consume[2] = {{CONS, 1,0} ,{BIN, 1, 0}};
- // ???????????
- int main() {
- key_t mem_key;
- my_key = ftok("my_file", 0);
- int shmid, semid, status;
- if ((shmid = shmget(mem_key, (num + 1) * sizeof(int), MY_FLAG)) == -1) {
- perror("shmget error");
- exit(1);
- }
- pos = shmat(shmid, 0, 0);
- buf = pos + sizeof(int);
- (*pos) = 0;
- if (*buf == -1) {
- perror("shmat error");
- exit(1);
- }
- if ((semid = semget(my_key, 3, MY_FLAG)) == -1) {
- perror("semget error");
- exit(1);
- }
- if ((semid = semget(my_key, 3, MY_FLAG)) == -1) {
- perror("semget error");
- exit(1);
- }
- semctl(semid, 2, SETVAL, 0);
- semctl(semid, 1, SETVAL, num);
- semctl(semid, 2, SETVAL, 1);
- srand(time(NULL));
- pid_t pid;
- if ((pid = fork()) == -1) {
- perror("Can't fork()");
- exit(1);
- }
- int k = 0;
- if (pid == 0) {
- while (k < count) {
- semop(semid, start_pr, 2);
- buf[*pos] = 1 + rand() % 10;
- printf("\tProduction^[%d] -- [%d]\n", k, buf[*pos]);
- (*pos)++;
- semop(semid, stop_pr, 2);
- sleep(rand() % 2);
- k++;
- }
- } else {
- while (k < count) {
- semop(semid, start_po, 2);
- (*pos)--;
- printf("Consumption^ [%d] -- [%d]\n", k, buf[*pos]);
- sleep(rand() % 2);
- k++;
- }
- }
- if (pid != 0) {
- if (shmdt(pos) == -1) {
- perror("shmdt error");
- exit(1);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement