We have a target system where we are trying to add shared memory using pthread mutex functions. We created a separate library that constructs and destructs memory and a set of functions defined which accesses shared memory. These functions are called from a daemon and other programs. Here is the following code
Code:
MemMan::MemMan()
{
lock();
key_t key = ftok("/lxi/pil/shmem.file", 133);
_created = false;
_size = sizeof(struct mydata);
mem_id = shmget(key, _size, 0666);
// Attempt to open existing shared memory
// with size to hold my structure
// and r/w access for all
if (mem_id != -1)
{
if (errno == ENOENT)
{
mem_id = shmget(key, _size, IPC_CREAT | 0666);
// Attempt to create shared memory
if (mem_id == -1)
{
printf("Failed to get memory\n");
return;
}
}
else
{
printf("Error creating shared mem\n");
return ;
}
_created = true;
}
_mydata = (struct mydata*)shmat(mem_id, NULL, 0);
// Attach it
mutex = &_mydata->mutex;
file_mutex = &_mydata->file_mutex;
pthread_mutex_init(mutex, NULL); // Only init content if this is first instance
pthread_mutex_init(file_mutex, NULL); // Only init content if this is first instance
_mydata->Flag = 0;
}
_created = true;
unlock();
}
MemMan::~MemMan()
{
struct shmid_ds stats;
shmctl(mem_id, IPC_STAT, &stats);
shmdt((void*)_mydata);
if( stats.shm_nattch <= 1)
{
shmctl(mem_id, IPC_RMID, NULL);
}
}
// Note: IPC_RMID on every destruct was causing problems, new app created new share !
// The above should do the IPC_RMID only on last destruct
}
int MemMan::stats(struct shmid_ds *stats)
{
return shmctl(mem_id, IPC_STAT, stats);
}
int MemMan::lock()
{
return pthread_mutex_lock(mutex);
}
int MemMan::unlock()
{
int result = pthread_mutex_unlock(mutex);
usleep(10000);
return result; // This stops mutex hogging by any one app
}
int MemMan::file_lock()
{
pthread_mutex_lock(file_mutex);
}
int MemMan::file_unlock()
{
pthread_mutex_unlock(file_mutex);
usleep(10000); // This stops mutex hogging by any one app
}
int MemMan::NumberOfClients()
{
struct shmid_ds stats;
shmctl(mem_id, IPC_STAT, &stats);
return stats.shm_nattch;
}
The functions are then defined like the following
Code:
int UTIL_GetFlag() {
if (mymem.Valid())
{
mymem.lock();
struct mydata *data = (struct mydata*)mymem.GetAddress();
mymem.unlock();
return data->Flag;
}
else
{
return -1;
}
}
The function (similar to one above) are accessing shared memory using daemon and other programs. The problem that we are experiencing are generally segmentation faults and target machine locking up. Since there is no debug capabilities on the target machine , its really difficult to step through the code. Its my first time with shared memory so I am not sure where I am going wrong. Can you please help?