I'm creating a client-server program that uses sockets to connect, once a client has connected to the server a new process is created for the client (required for project). I have a linked list in the server that stores client structs holding info about them.
The issue that this has created is that when 2 clients connect for example, each client can only view there version of the linked list which holds just there details. So i'm trying to create a shared memory segment that holds the linked list, but i'm new to shared memory and am struggling to get it to work.
node_t *client_list = NULL;
int main() {
int shmid;
key_t key;
key = 1234;
shmid = shmget(key, SHMSZ, IPC_CREAT | 0666);
client_list = (node_t *) shmat(shmid, (void *)0, 0);
while(1) {
pid_t current_process;
if ((current_process = fork()) == 0) {
node_add(client_list, &client);
node_print(client_list);
pthread_create(&thread[client_count], NULL, network(client.ID), (void *) &client);
}
return 0;
}
(I have left socket connection code etc off to make it more readable). I am probably doing something very wrong in this current version but my understanding was I am creating a shared memory segment for 'node_t *client_list' which is a linked list, and then after a new process is created from connection a client node added to it. Any help would be greatly appreciated.
selectis a really efficient way to handle multiple sockets, and really alleviates the race condition question. It's very performant too, usually, because you spend most of your time waiting for a client not processing. If you are going to use shared memory etc, fine, but you're still going to need some sort of coordination mechanism to make sure the shared memory is consistent.forking _andpthread_createing? strange. but you're absolutely right about the problem - aforkis going to duplicate the process memory space. Shared memory is a solution for sharing data across thefork; memory is already shared between threads but I'm not really sure what the pthread_create is supposed to be doing. You'll also need a read/write lock to make sure one process isn't writing the memory while another is reading it or you'll get inconsistent results.