简体   繁体   English

C ++-进程之间共享互斥

[英]C++ - Mutex Shared Between Processes

I am trying to create a system that consists of a server and several clients that are attempting to communicate with each other. 我正在尝试创建一个由服务器和几个试图相互通信的客户端组成的系统。 The clients place data into shared memory (created using ftok / shmget), and then are able to write data into this memory. 客户端将数据放入共享内存(使用ftok / shmget创建),然后将数据写入此内存。 These consist of 2 separate programs. 这些由2个单独的程序组成。

The server reads values that the clients write into the shared memory, and write them to a file. 服务器读取客户端写入共享内存的值,并将其写入文件。 I can get the clients to write data to the shared memory, and the server to read the data, but I am having trouble with locking the shared memory so multiple clients don't write at the same time. 我可以让客户端将数据写入共享内存,让服务器读取数据,但是我在锁定共享内存时遇到了麻烦,因此多个客户端不能同时写入。

I tried creating a semaphore (using sem_open), but this is not shared between the processes. 我尝试创建一个信号量(使用sem_open),但是进程之间没有共享此信号量。 How do I go about sharing the semaphore between processes (or mutexes, as these would probably work better)? 我该如何在进程之间共享信号量(或互斥体,因为它们可能会更好地工作)?

You want to use a named semaphore or mutex: 您要使用命名信号量或互斥量:

int permissions = 0644;
sem_t *shared_sem;
unsigned int inital_value = 1;

shared_sem = sem_open("SharedSem", O_CREAT, permissions, inital_value);

Also, make sure you set the permissions correctly. 另外,请确保正确设置权限。

使用“命名”信号量...例如两个进程都使用的“ / someuniquename”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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