shared memory confusion

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm using the shmop_* functions to create and access shared memory.  I've
never used shared memory before, so I apologize if my reasoning is
completely off...

$shm_id = shmop_open(ftok(__FILE__, 'a'), "c", 0600, 32);

That works for the first process, but if I try to launch a second process it
gives me the warning "Unable to create or attach shared memory" and fails.

According to the PHP manual, the 'c' flag will create shared memory, or if
one with the same key already exists, then it will open it for read/write
access - so I'm not sure why doesn't work (should it?).  The manual page
mentions the last two args should be zero if I'm opening an existing memory
segment, but I don't know if I'm opening an existing segment when I execute
that line.

According to one of the manual comments, I can determine whether the memory
segment has been allocated already using the 'ac' flag:

1) $shm_id = shmop_open(ftok(__FILE__, 'a'), 'ac', 0, 0);
2) if(!$shm_id){
3)    $shm_id = shmop_open(ftok(__FILE__, 'a'), 'c', 0600, 32);
4) }

But what happens if there is a context switch immediately after line 2 has
finished executing?  Then two processes could both end up executing line 3,
and I'll get that warning again.   Should I just use a semaphore to make
this atomic?

( linux 2.6, php 4.3.8)

Re: shared memory confusion

Jim wrote:

Quoted text here. Click to load it
Maybe this is obvious...but did you close the shm before accessing it from
the second instance? Maybe it's locked?



Re: shared memory confusion

No, the first process doesn't close it until just before it exits, so the
shared memory should still be available.
I'm not sure what you mean by 'locked' - how could it be locked?  All the
processes are running as the same user, so the permission 0600 shouldn't
deny the other processes access.


Quoted text here. Click to load it

Site Timeline