简体   繁体   中英

posix shared memory creation in thread

I am new to to Linux programming, so please be gentle! . 方案说明

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.

if you are trying to access a file descriptor made by another process, it will not work. File descriptors are only good in the process they were created in. Im only saying this because of the error you are seeing.

But you have the right idea for sharing memory, you can either make a shared segment of mapped memory to both processes, which may get hairy with race conditions with multiple threads in each process competing to access it, or you could create a socket, and have your two processes communicate through that, or a pipe.

I would recommend an AF_UNIX socket for IPC like you're trying to achieve.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM