0

我正在使用 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 结构处理多个客户端?

4

1 回答 1

0

If you use a single instance of Comm, then the server plus all clients would share that one struct to do all communication. That implies sem_wait/sem_post around all accesses, while shuffling the clientPid and the remainder of the struct variables to match the currently active client.

It would seem more straightforward to allocate the array of structs, with the server manipulating the whole range of structs, while each child would only access one of the array elements (granted, it can see them all but would only deal with one). Then each set of semaphores per Comm element would be used to coordinate communication between the server and a particular client. The assumption here is the clients have no communication between themselves.

于 2013-11-23T18:53:00.937 回答