Добавил:
nickolai_oreschenko
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:УТС 4 семестр / Lab6_Oreshchenko / main2
.cpp#include <pthread.h>
#include <iostream>
#include <semaphore.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
bool flag = true;
sem_t* sem; // "семафор для считывания"
sem_t* sem_Ack; // "семафор для записи"
int proj = 1;
key_t key = ftok("null.txt", proj);
void* ptr;
void* func(void* arg)
{
int count;
while(flag){
sem_wait(sem);
memcpy(&count, ptr, sizeof(int));
std::cout << count << std::endl;
sem_post(sem_Ack);
sleep(1);
}//w hile
pthread_exit(NULL);
}// func
int main()
{
int mem_id = shmget(key, 4096, IPC_CREAT|0666); // создаём участок разделяемой памяти
ptr = (int*)shmat(mem_id, NULL,0); // подсоединяем к адресному простр-ву процесса
// создание семафоров
sem = sem_open("/semaphore", O_CREAT, 0644, 0);
sem_Ack = sem_open("/ack_semaphore", O_CREAT, 0644, 0);
pthread_t thread;
pthread_create(&thread, NULL, &func, NULL);
getchar();
flag = false;
pthread_join(thread, NULL);
sem_close(sem);
sem_unlink("/semaphore");
sem_close(sem_Ack);
sem_unlink("/ack_semaphore");
shmdt(ptr); // отсоединяем от адресного пр-ва
shmctl(mem_id, IPC_RMID, (shmid_ds*)ptr); // удаляем
return 0;
}