I am trying to compile a code using pointer in a shared memory. I'd like to use mutex variable to examine whether interprocess synchronization is possible. But Xcode gives me the error "Parse Issue "Expected Expression" and highlights the line
*(pthread_mutex_t*)shm_addr = PTHREAD_MUTEX_INITIALIZER;
in red.
Here is the code.
#include <sys/ipc.h>
#include <sys/shm.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define KEY_NUM 9527
#define MEM_SIZE 4096
pthread_mutex_t test;
int main(int argc, char * argv[])
{
int shm_id;
void *shm_addr;
if( (shm_id = shmget((key_t)KEY_NUM, MEM_SIZE, IPC_CREAT | 0666)) == -1)
{
printf("fail to allocate a shared memory.\n");
return -1;
}
if((shm_addr = shmat(shm_id, (void*)0,0)) == (void*)-1)
{
printf("fail to attach shared memory.\n");
return -1;
}
*(pthread_mutex_t*)shm_addr = PTHREAD_MUTEX_INITIALIZER; // error.
test = PTHREAD_MUTEX_INITIALIZER;
// this statement works well.
*(int*)(shm_addr+64) = 10000; // this statement also works well.
// information useful to you.
// sizeof(pthread_mutex_t*) : 64
// OS X Mountain Lion 64bits
return 0;
}
I have no idea why. Can anyone help?
Thank you.