2

I have seen that question on SO already but it wasn't clear to me the following case:

A shm has been created. So if I call in my case:

int shmid = shmget(key, sizeof(struct messageQueue), IPC_CREAT | S_IRWXU | IPC_EXCL);

shmid turns -1 if the shm already exists. But can i somewhere get it's ID? Or do I need to call shmget(...) without EXCL flag again in order to get the ID?

Thanks in advance

RKou
5,4193 gold badges14 silver badges38 bronze badges
asked Jan 18, 2021 at 18:00
2
  • I think you have to call it again. This sounds like an XY problem, what is the overall goal? Commented Jan 18, 2021 at 18:12
  • 2
    When it returns error with EXCL and CREAT, just call it again without EXCL and CREAT to get an id. Commented Jan 18, 2021 at 18:13

1 Answer 1

3

Normally, IPC_CREAT | IPC_EXCL is used if you want to create and initialize a new memory block. E.g.:

int shmid = shmget(key, sizeof(struct messageQueue), IPC_CREAT | S_IRWXU | IPC_EXCL);
if( shmid != -1 )
{
 /* initialization code */
}
/* if it already exists, open it: */
if( shmid == -1 && errno == EEXIST ) 
 shmid = shmget(key, sizeof(struct messageQueue), S_IRWXU );
if( shmid == -1 ) {
 perror("shmget");
}

If you don't need to initialize it, you can skip the IPC_EXCL:

int shmid = shmget(key, sizeof(struct messageQueue), IPC_CREAT | S_IRWXU );

and if you don't need to create it, you can skip the IPC_CREAT:

int shmid = shmget(key, sizeof(struct messageQueue), S_IRWXU );
answered Jan 19, 2021 at 13:09
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.