2013-11-23 141 views
0

我正在實現使用POSIX共享內存和未命名信號量的客戶端服務器。期望服務器同時處理多個客戶端。該代碼適用於單個客戶端,但不適用於多個客戶端。 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[max_clients]而不是我目前使用的(單個Comm結構)?對於每個客戶端,服務器都需要管理Comm陣列並將適當的元素從該陣列返回給客戶端。客戶端反過來將使用該塊來同步Comm元素中信號量的操作?或者多個客戶端可以使用單個Comm結構進行處理?

回答

0

如果您使用Comm的單個實例,那麼服務器加上所有客戶端將共享該一個結構來完成所有通信。這意味着圍繞所有訪問都使用sem_wait/sem_post,同時對clientPid和其餘結構變量進行混洗,以匹配當前活動的客戶端。

分配結構數組似乎更直接,服務器操縱整個結構範圍,而每個孩子只會訪問其中一個數組元素(授予,它可以看到它們,但只處理一)。然後,每個Comm元素的每組信號將用於協調服務器和特定客戶端之間的通信。這裏的假設是客戶之間沒有溝通。