View Single Post

   
  #2 (permalink)  
Old 03-20-2008, 12:42 PM
Don Morris
 
Posts: n/a
Default Re: Detect if a segment existes in sharred memoty

Alex Vinokur wrote:
>> uname -smrsv

> HP-UX B.11.23 U ia64


Note on the below -- if you add PA into the mix, there an additional
problem of a binary using your functions where chatr +q4p enabled was
used [Q4 private process]. Such a process gets EFAULT on any
shmget() call [since there's no shared address space for it to use].
ia64 chatr does not allow this option according to the man page and
my knowledge, hence I won't discuss it further... but beware if you're
writing a library that will be compiled on PA as well.

>
>
> Here are two functions to detect if some segment exists in shared
> memory.
>
>
> bool shmSegmentExists(key_t key)
> {
> if ((shmget(key, 0, myFlags | IPC_CREAT | IPC_EXCL) == -1)


You don't define myFlags anywhere I can see. An incorrect flag
to shmget() can yield EINVAL, you'll falsely return that the
segment does not exist. Since in this case you're only checking
for segment existence and explicitly plan to fail on actual
creation, I'd lose myFlags entirely and just pass (IPC_CREAT|IPC_EXCL).

If your key is IPC_PRIVATE you'll fail with ENOSPC (no segments
left) or EINVAL [0 sized segment not allowed]. Technically, asking
if a private key segment already exists without knowing the shmid
is a weird op anyway -- each call to shmget() with IPC_PRIVATE is
supposed to create a new segment in the first place... so failing
to consider a brand new segment which you failed to create as
existing is reasonable, though an odd exercise in logic.


> {
> if (errno == EEXIST)
> {
> return true;
> }
> }
>
> return false;
> }
>
> bool shmSegmentIsAbsent(key_t key)
> {
> assert (!(myFlags & IPC_CREAT));
> if ((shmget(key, 0, myFlags) == -1)


Again, key == IPC_PRIVATE could give ENOSPC or EINVAL here.

Other invalid flags or flag combinations could give EINVAL.

> {
> if (errno == ENOENT)
> {
> return true;
> }
> }
>
> return false;
> }
>
>
> --------------------------
>
> 1. Are those functions valid?


With the caveats listed, I believe so, yes.

>
> 2. If the functions are indeed valid, is this always true:
> assert (shmSegmentExists(key) == !shmSegmentIsAbsent (key));


Not if key is IPC_PRIVATE (both return False, False != True) or
for illegal flags (i.e. again, see caveats).

In general and with appropriate pre-checks, it should hold.

Don
--
kernel, n:
A part of an operating system that preserves the medieval traditions
of sorcery and black art.
Reply With Quote