I have a strange problem with shared memory.
Method shmget returns -1 and errno is set to EEXIST. According to man, it is only possible when both flag IPC_EXCL and IPC_CREAT are provided.
My code:
int main()
{
int shmid = shmget(0xABCD, MAX_SIZE, IPC_CREAT | 0x660);
int shmid2 = shmget(0xABCD, MAX_SIZE, IPC_CREAT | 0x660 );
if(shmid == -1)
{
if(errno == EEXIST)
perror("Error");
return -1;
}
if(shmid2 == -1)
{
if(errno == EEXIST)
perror("Error2");
return -1;
}
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
It compiles with -Wall without warnings, I check with ipcs if the segment is already present (and remove it if needed). The output is Error2: File exists.
It works when I change the second shmget to:
int shmid2 = shmget(0xABCD, MAX_SIZE, 0 );
Quote from man shmget:
EEXIST IPC_CREAT | IPC_EXCL was specified and the segment exists.
And one more question: is it true, that mode_flags (i.e. 0x660) are not used when trying to execute shmget?
Permission modes need to be specified in octal, not hexadecimal.
0x660(hex) =03140(octal). And theIPC_EXCLflag has the octal value02000in the Linux ABI — so by using0x660instead of0660you are accidentally settingIPC_EXCL, which is why you get the error.If I change both instances of
0x660to0660in your program and fix the other things that make it not compile (notably, you left out all the headers and the definition ofMAX_SIZE) it works as expected.