posix为多个客户端共享内存

时间:2013-11-23 10:50:35

标签: c posix semaphore memory-mapping

我正在使用POSIX共享内存和未命名的信号量实现客户端服务器。期望服务器同时处理多个客户端。该代码适用于单个客户端,但不适用于多个客户端。 POSIX操作由

管理
enum { MAX_MSG = 256 };
enum { CLIENT_SEM,          // semaphore is 1 if server is available for use by client    
       MSG_FOR_DAEMON_SEM,  // semaphore is 1 if shm contains msg for daemon    
       MSG_FOR_CLIENT_SEM,  // semaphore is 1 if shm contains msg for client    
       MSG_FOR_SERVER_SEM,  // semaphore is 1 if shm contains msg for server    
       N_SEMS };

typedef struct {    
    sem_t  sems[N_SEMS]; // semaphore sent for sync   
    pid_t  clientPid;    // pid of current client    
    char   msg[MAX_MSG]; // current message being sent    
    int    max_matrix_size; //max rows a square matrix can have 
}Comm;

// server calls setup_comm with doCreate=1 and creates shared mem of size max_clients * sizeof(Comm) 
// client calls setup_comm with doCreate=0 and in return gets the mmap pointer to the shared memory created by the server 
Comm* setup_comm(const char *shmPosixName, int doCreate, int max_clients);

问题是,要处理多个客户端,我们是否需要维护一个Comm结构数组;那是Comm[max_clients]而不是我目前使用的(单个Comm结构)?对于每个客户端,服务器需要管理Comm数组并将适当的元素从该数组返回给客户端。客户端又将使用该块来同步Comm元素中信号量的操作?或者可以使用单个Comm结构处理多个客户端?

1 个答案:

答案 0 :(得分:0)

如果您使用单个Comm实例,那么服务器和所有客户端将共享该一个结构以进行所有通信。这意味着sem_wait / sem_post围绕所有访问,同时改组clientPid和其余结构变量以匹配当前活动的客户端。

分配结构数组似乎更直接,服务器操纵整个结构范围,而每个子进程只能访问其中一个数组元素(被授予,它们可以看到它们但只能处理一个)。然后,每个Comm元素的每组信号量将用于协调服务器和特定客户端之间的通信。这里的假设是客户之间没有沟通。