Hi,
I am happy to be with this forum for the first time and so let me say "hi" to every body.Trying the Mutex between shared process is new to me.
Now i am trying to write simple socket IPC mechanism on Linux using server and client.Server will create shared memory with mutex and buffer and same mutex initialized with flag PTHERAD_SHARED_PROCESS and different clients will access this shared memory and update their message.
When i run server it is able to create the shared memory and mutex initialization everything is cool but when i run different clients they try to attach this shared memory and acquire the lock, all of them were able to quire the lock.
so it looks like mutex is not shared among process.
Please suggest me what am I missing.
Code:
Code Snippet On Server Side Done:
key_t key = 5678;
if ((shmid = shmget(key, 27, IPC_CREAT | 0666)) < 0)
{
std::cout<< "Failed to create shared Memory::"<<strerror( errno )<<std::endl;
exit(1);
}
if ((lockptr = (shLock*)shmat(shmid, NULL, 0)) == (shLock *) -1)
{
std::cout<< "Failed to attach shared Memory::"<<strerror( errno )<<std::endl;
exit(1);
}
memset( lockptr->buffer,0,sizeof( lockptr->buffer) );
char d[] = "REDYYYYYYYYYYYYYYYYYYYYYYYYYY";
memcpy( lockptr->buffer,d,strlen( d ) );
if( pthread_mutexattr_init( &lockptr->mutexAttr ) == 0 )
std::cout<< "shared mutex attr intialized"<<std::endl;
if( pthread_mutexattr_setpshared( &lockptr->mutexAttr,PTHREAD_PROCESS_SHARED) == 0 )
std::cout<< "shared mutexattribute set"<<std::endl;
if( pthread_mutex_init( &lockptr->mutex, &lockptr->mutexAttr) == 0 )
std::cout<< "shared mutex intialized"<<std::endl;
Clent SIde Code:
key_t key = 5678;
if ((shmid = shmget(key, 27, 0666)) < 0)
{
std::cout<< "Failed to create shared Memory::"<<strerror( errno )<<std::endl;
exit(1);
}
if ((lockptr = (shLock*)shmat(shmid, NULL, 0)) == (shLock *) -1)
{
std::cout<< "Failed to attach shared Memory::"<<strerror( errno )<<std::endl;
exit(1);
}
pthread_mutex_lock( &lockptr->mutex );
std::cout<< "Enter the data to send "<<std::endl;
// NOTE: i am not releasing the lock for test purpose only to make sure it is working correctly when different clients try to acquire same
Thanks In Advance
Brahma