Reputation: 55
I am writting project in c using shared memory via shm functions. I want to try to "connect" to shared memory and check if it exists using shmget() function.
I tried a few flags with this function but failed to achieve expected result. I wonder if there is a way to see whether a shared memory already exists.
Upvotes: 1
Views: 978
Reputation: 26345
The manual page
spells this out rather explicitly.
int shmget(key_t key, size_t size, int shmflg);
If shmflg specifies both IPC_CREAT and IPC_EXCL and a shared memory segment already exists for key, then shmget() fails with errno set to EEXIST.
And again, the flags:
IPC_CREAT
- Create a new segment. If this flag is not used, then shmget() will find the segment associated with key and check to see if the user has permission to access the segment.
IPC_EXCL
- This flag is used with IPC_CREAT to ensure that this call creates the segment. If the segment already exists, the call fails.
Alternatively, if the flag IPC_CREAT
is not specified, and no memory segment exists for the given key
, then shmget
fails and sets errno
to ENOENT
.
ENOENT
- No segment exists for the given key, and IPC_CREAT was not specified.
So you may want to try something along the lines of
errno = 0;
if (-1 == shmget(key, size, IPC_CREAT | IPC_EXCL)) {
if (EEXIST == errno) {
/* shared memory already exists */
}
}
or
errno = 0;
if (-1 == shmget(key, size, 0)) {
if (ENOENT == errno) {
/* shared memory does not exist */
}
}
On the other hand, ftok(3)
fails for the same reasons as stat(2)
.
Upvotes: 2