Receiving the message “Invalid argument” when using shmget with the second parameter not being NULL.
It compiles ok, but when executing, I get this error message.
I’ve been stuck on this all day long. Hope you can help me! 🙂
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int idSharedMem;
int *varSharedMem1;
int *varSharedMem2;
/* Create the shared memory */
idSharedMem = shmget((key_t) 0001, sizeof(int), IPC_CREAT | 0666);
if (idSharedMem == -1)
{
perror("shmget");
}
/* Allocate a memory address and attached it to a variable */
varSharedMem1 = shmat(idSharedMem, NULL, 0);
if (varSharedMem1 == (int *) -1)
{
perror("shmat1");
}
/* Sign a value to the variable */
*varSharedMem1 = 5;
/* Attach an existing allocated memory to another variable */
varSharedMem2 = shmat(idSharedMem, varSharedMem1, 0);
if (varSharedMem2 == (int *) -1)
{
/* PRINTS "shmat2: Invalid argument" */
perror("shmat2");
}
/* Wanted it to print 5 */
printf("Recovered value %d\n", *varSharedMem2);
return(0);
}
With
shmat(idSharedMem, varSharedMem1, 0);you’re trying to attach the segment at the location ofvarSharedMem1. However you have previously attached a segment at that location which will result in EINVAL. Linux provides a SHM_REMAP flag you can use to replace previously mapped segments.shmat manpage: