3

From PHP, it says

int shmop_open ( int $key , string $flags , int $mode , int $size )

where $key is the

System's id for the shared memory block. Can be passed as a decimal or hex.

Some people fill the $key with an arbitrary number(1) while others uses a file to obtain the $key value(2). Is the $key a random value?.

(1)

   $shm_id = shmop_open(987654, "c", 0644, 100);

(2)

   $shm_key = ftok(__FILE__, 't');
   $shm_id = shmop_open($shm_key, "c", 0644, 100);

Btw, in windows, i used a small number and while it worked, i was limited to use up to 1024 bytes. While using a big number for the key, i was able to address more memory. Why?.

magallanes
  • 6,583
  • 4
  • 54
  • 55

1 Answers1

5

If you look through the source of shmop_open(), you will see that the function is basically a wrapper around the POSIX shmget(), shmctl(), and shmat() routines. You can see that the $key parameter to shmop_open() is passed as the System V IPC key to shmget().

shmget() returns the identifier of the shared memory segment associated with the given key. If the key passed to shmget() is the special value IPC_PRIVATE, then this refers to a unique shared memory segment that can only be inherited by descendent processes created by fork() (Note that this is probably not relevant to your case). Otherwise, in order for two processes to access the same shared memory segment, they need to get that segment's identifier using the same key.

You can use a fixed key, like the first example you cited. However, using fixed keys is prone to inadvertent collisions.

A better approach is to use ftok(). If you consistently use ftok() to generate the key, then the risk of collisions is lower as a result of ftok()'s guarantee that the generated key will be different when called with different id values or with paths that name two different files existing on the same file system at the same time.

See How to choose the "Key" for inter-processes communication in Linux?

PHP on Windows does not natively support the shared memory functions. Instead, they are emulated via the "thread-safe resource manager" (TSRM). You can find the TSRM implementation of shmget() in TSRM/tsrm_win32.c. The TSRM shared memory emulation is known to be somewhat quirky (e.g. see this answer).

One thing that seems odd to me is that the TSRM shmget() implementation constructs a Windows File Mapping name representing the shared memory segment via:

char shm_segment[26], shm_info[29];
/* ... */
snprintf(shm_segment, sizeof(shm_segment)-1, "TSRM_SHM_SEGMENT:%d", key);

Because the length of "TSRM_SHM_SEGMENT:" is 17 and this call to snprintf() will write at most 24 characters, this leaves only 7 characters for the key. Thus, it appears that only keys between -999999 and 9999999, inclusive, should be used with PHP on Windows.

Community
  • 1
  • 1
Daniel Trebbien
  • 38,421
  • 18
  • 121
  • 193