Search code examples
cmultithreadingpthreadsposixshared-memory

posix shared memory creation in thread


I am new to to Linux programming, so please be gentle! .scenario description

I am trying to implement the above scenario. Here two process are created using fork() each with N number of threads. Threads from process 1 create a request and enqueue it on the queue 1. Threads from process 2 dequeue a request and send a response back on queue 2. Each request consists of shmid and size where shmid is a shared memory segment generated like this -

shmid = shm_open(<a random string>, O_CREAT | O_RDWR | O_TRUNC, S_IRWXU | S_IRWXG);

if (shmid < 0) {
    perror("failure on shm_open");
    exit(1);
}
if (ftruncate(*share, size) == -1) {
    perror("Error on ftruncate\n");
    exit(-1);
}

I am able to open and modify this shared memory segment immediately in the same thread after creation using

void* request = mmap(NULL, size, PROT_WRITE, MAP_SHARED, shmid, 0);
memset(str, 'w', size);

After this I pass on the shmid to process 2 using queue 1.

My problem is when the threads in process 2 try to open this shmid using the same way, I get a EBADF: fd is not a valid file descriptor error. I have verified that the shmid is correct after dequeuing by printing the value in both process 1 and 2.

Is creating shared memory segments between processes not possible when they are created from a different process/thread? Any ideas on how I can get this to work?

Please let me know if more information is needed.


Solution

  • The shared memory segment must be opened in both processes.

    If both processes are created by fork() from a common parent, then you can just do the shm_open() prior to the fork(), and it will be inherited by both child processes.

    Alternatively, each process can call shm_open(), passing the same value for the name parameter.