I'm using shmget for sharing data between processes of my project on Linux.
int shmget(key_t key, size_t size, int shmflg);
However, any other programs can call to shmget too, and thus it may lead to key conflict (because I use a constant as the key to call shmget, I must use a constant instead of a generated key because the lateral processes are built and run separately).
What should be the safe values to be used as key in shmget?
There are no safe values, and you (and every other process creating shared segment) should use IPC_EXCL
to ensure there is no collision. However, the latter should ensure that other programs don't start writing into your segment (unless they are written badly).
You can try building your 'private' key constant off ftok() but well, you know it ain't safe. If you collide with something, you won't have a way to tell your programs that this is not the right key. Also remember that:
Only the low-order 8-bits of
id
are significant. The behavior of ftok() is unspecified if these bits are 0.
In other words, don't pass 0
there ;).
In any case, you should seriously consider creating some channel of communication. A single file written by the server with id would be enough, which would be then read by other programs.
From other ideas, you may try passing server PID as id
, if other processes can get at least that. This could make it a bit 'safer'.
I suggest you use the POSIX shm_open
(with mmap
) instead, It doesn't have the problem of collisions that exists with ftok
so long as you aren't using the same named region as other software.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With