这是结构:
typedef struct Queue {
int data[MAX_SIZE];
long front;
long back;
int size;
int mysize;
} Queue;
这是代码:
if((queueShmid = shmget(IPC_PRIVATE, sizeof(Queue), IPC_CREAT | IPC_EXCL ))==-1) {
printf("Shared memory segment exists - opening as client\n");
/* Segment probably already exists - try as a client*/
if((queueShmid = shmget(IPC_PRIVATE, 2*sizeof(Queue), 0)) == -1)
{ perror(" bad shmget"); exit(1);}
}
Queue *queue = (Queue*) shmat(queueShmid, NULL, 0);
if(queue=NULL) {
perror("bad shmat"); exit(1);
}
if ((int) queue < 0) {
printf("shmat() failed %d \n",(int)queue); exit(1);
}
printf ("shared memory attached at address %p\n", queue);
返回:共享内存附加地址(nil),
任何其他共享内存都运行良好,任何想法?
答案 0 :(得分:0)
my comments are prefixed with '// <--'
suggest OP read the documentation on system calls, especially the returned values
typedef struct Queue
{
int data[MAX_SIZE];
long front;
long back;
int size;
int mysize;
} Queue;
if((queueShmid = shmget(IPC_PRIVATE, sizeof(Queue), IPC_CREAT | IPC_EXCL ))==-1)
{
printf("Shared memory segment exists - opening as client\n");
// <-- should verify errno is EEXIST (Segment exists, cannot create)
// <-- rather than making any assumptions
/* Segment probably already exists - try as a client*/
// <-- it was a single queue instance above so why is it 2 times that size below???
if((queueShmid = shmget(IPC_PRIVATE, 2*sizeof(Queue), 0)) == -1)
{
//perror(" bad shmget");
perror( "shmget failed for 2 times size of queue" );
exit(1);
} // end if
} // end if
Queue *queue=(Queue*)shmat(queueShmid, NULL, 0);
//if(queue=NULL) // <-- placing the literal on the left would have enabled the compiler to catch this error
if(queue==NULL) // <-- on error, shmat returns (void*)-1 (not NULL) and sets errno
{
perror( "shmat for ptr to instance of queue failed" );
//perror("bad shmat");
exit(1);
}
if ((int) queue < 0)
{
printf("shmat() failed %d \n",(int)queue); exit(1);
}
printf ("shared memory attached at address %p\n", queue);