Ошибки в программе
Помогите исправить пожалуйста ошибки в проге
ошибки:
Задание звучит так: реализовать прогу копирующ. файл произвольного размера блоками по 128 байт через буфер 1кбайт
Заранее спасибо!
Помогите исправить пожалуйста ошибки в проге
Код:
#include <cstdlib>
#include <iostream>
//#include <ifstream>
#include <fstream>
#include <memory>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <errno.h>
using namespace std;
template <class T>
class SharedMemory
{
private:
int shmid; // IPC дескриптор для области разделяемой памяти
key_t key; // IPC ключ
char *pathname;
SharedMemory(const Thread& copy); // copy constructor denied
public:
SharedMemory(int size)
{
if((key = ftok(pathname,0)) < 0)
{
cout << "Can\'t generate key" << endl;
exit(-1);
}
if((shmid = shmget(key, size, 0666 | IPC_CREAT | IPC_EXCL)) < 0)
{
/* В случае ошибки пытаемся определить: возникла ли она
из-за того, что сегмент разделяемой памяти уже существует
или по другой причине */
if(errno != EEXIST)
{
/* Если по другой причине – прекращаем работу */
cout << "Can\'t create shared memory" << endl;
exit(-1);
} else {
/* Если из-за того, что разделяемая память уже
существует, то пытаемся получить ее IPC дескриптор */
if((shmid = shmget(key, size, 0)) < 0)
{
cout << "Can\'t find shared memory" << endl;
exit(-1);
}
}
}
~SharedMemory(); { shmdt(shmem); }
T attach(); { return (T)shmat(shmid, 0, 0); }
int detach(); { return shmctl(shmid, IPC_RMID, 0); }
}};
class Semaphore
{
private:
key_t key;
int count;
int shmid;
sembuf buf;
public:
Semaphore() {}
Semaphore(char *pathname)
{
/* Генерируем IPC-ключ из имени файла в текущей
директории и номера экземпляра массива семафоров 0 */
if((key = ftok(pathname, 0)) < 0) {
printf("Can\'t generate key\n");
exit(-1);
}
/* Пытаемся получить доступ по ключу к массиву
семафоров, если он существует, или создать его из одного
семафора, если его еще не существует, с правами доступа
read & write для всех пользователей */
if((semid = semget(key, 1, 0666 | IPC_CREAT)) < 0){
printf("Can\'t get semid\n");
exit(-1);
}
}
~Semaphore() { semctl(semid, 0, 2, IPC_RMID); }
void lock()
{
buf.sem_op = -1;
buf.sem_flg = 0;
buf.sem_num = 0;
semop(semid, &buf, 1);
}
void unlock()
{
buf.sem_op = 1;
buf.sem_flg = 0;
buf.sem_num = 0;
semop(semid, &buf[1], 1);
}
};
// Класс потока
class Thread
{
private:
pthread_t thread;
Thread(const Thread& copy); // copy constructor denied
static void *thread_func(void *d) { ((Thread *)d)->run(); }
public:
Thread() {}
virtual ~Thread() {}
virtual void run() = 0;
int start() { return pthread_create(&thread, NULL,
Thread::thread_func, (void*)this); }
int wait () { return pthread_join (thread, NULL); }
};
struct memory
{
int status; // 1 - поток производитель работает, 0 - поток закончил свою работу
char bytes[1024];
};
// Производитель
class Producer: public Thread
{
private:
public:
void run()
{
Semaphore mutex;
SharedMemory<memory*> mem(sizeof(memory));
memory *buf = mem.attach();
mutex.lock();
ifstream file("read.txt"); //reading a file
if (!file.is_open())
{
cout << "Can`t open file read.txt." << endl;
exit(-1);
}
while (!file.eof())
{
mutex.lock();
file.read(memory->buf, 1024);
memory->status = 1;
mutex.unlock();
}
memory->status = 0;
read.close();
}
};
// Потребитель
class Consumer: public Thread
{
public:
void run()
{
Semaphore mutex;
SharedMemory<memory*> mem(sizeof(memory));
memory *buf = mem.attach();
ofstream file("write.txt");//writing to a file
if (!file.is_open())
{
cout << "Can`t open file read.txt." << endl;
exit(-1);
}
while (memory->status)
{
mutex.lock();
file.write(memory->buf, 1024);
mutex.unlock();
}
file.close();
}
};
typedef std::auto_ptr<Thread> ThreadPtr;
int main(int argc, char *argv[])
{
ThreadPtr a(new Producer());
ThreadPtr b(new Consumer());
if (a->start() != 0 || b->start() != 0)
return 1;
if (a->wait() != 0 || b->wait() != 0)
return 1;
return 0;
}
ошибки:
Код:
g++ semaphor.cc
semaphor.cc:24:24: error: ‘Thread’ does not name a type
semaphor.cc:24:32: error: ISO C++ forbids declaration of ‘copy’ with no type
semaphor.cc: In constructor ‘SharedMemory<T>::SharedMemory(int)’:
semaphor.cc:57:30: error: ‘shmem’ was not declared in this scope
semaphor.cc:59:46: error: returning a value from a constructor
semaphor.cc:60:53: error: returning a value from a constructor
semaphor.cc: In constructor ‘Semaphore::Semaphore(char*)’:
semaphor.cc:89:13: error: ‘semid’ was not declared in this scope
semaphor.cc: In destructor ‘Semaphore::~Semaphore()’:
semaphor.cc:95:27: error: ‘semid’ was not declared in this scope
semaphor.cc: In member function ‘void Semaphore::lock()’:
semaphor.cc:103:15: error: ‘semid’ was not declared in this scope
semaphor.cc: In member function ‘void Semaphore::unlock()’:
semaphor.cc:111:15: error: ‘semid’ was not declared in this scope
semaphor.cc:111:28: error: no match for ‘operator[]’ in ‘((Semaphore*)this)->Semaphore::buf[1]’
semaphor.cc: In member function ‘virtual void Producer::run()’:
semaphor.cc:150:49: error: call of overloaded ‘SharedMemory(unsigned int)’ is ambiguous
semaphor.cc:26:5: note: candidates are: SharedMemory<T>::SharedMemory(int) [with T = memory*]
semaphor.cc:24:5: note: SharedMemory<T>::SharedMemory(const int&) [with T = memory*]
semaphor.cc:18:1: note: SharedMemory<memory*>::SharedMemory(const SharedMemory<memory*>&)
semaphor.cc:151:27: error: ‘class SharedMemory<memory*>’ has no member named ‘attach’
semaphor.cc:165:29: error: expected primary-expression before ‘->’ token
semaphor.cc:166:19: error: expected unqualified-id before ‘->’ token
semaphor.cc:170:15: error: expected unqualified-id before ‘->’ token
semaphor.cc:171:14: error: request for member ‘close’ in ‘read’, which is of non-class type ‘ssize_t(int, void*, size_t)’
semaphor.cc: In member function ‘virtual void Consumer::run()’:
semaphor.cc:182:49: error: call of overloaded ‘SharedMemory(unsigned int)’ is ambiguous
semaphor.cc:26:5: note: candidates are: SharedMemory<T>::SharedMemory(int) [with T = memory*]
semaphor.cc:24:5: note: SharedMemory<T>::SharedMemory(const int&) [with T = memory*]
semaphor.cc:18:1: note: SharedMemory<memory*>::SharedMemory(const SharedMemory<memory*>&)
semaphor.cc:183:27: error: ‘class SharedMemory<memory*>’ has no member named ‘attach’
semaphor.cc:192:22: error: expected primary-expression before ‘->’ token
semaphor.cc:195:30: error: expected primary-expression before ‘->’ token
Задание звучит так: реализовать прогу копирующ. файл произвольного размера блоками по 128 байт через буфер 1кбайт
Заранее спасибо!