I am trying to create a simple server-client program (a primitive bulettin board)
Up to now I have created the listening socket bind()ed it and I am accepting in a for(; loop. Right now when someone tries to connects to read the topics and replies I call fork() to create a separate process for handling that client. I know that fork basically creates a copy of the address space of the parent process, so what I am confused about is this:
Inside the infinite for the very first command is accept() and after that fork. Inside the child process I can use the file descriptor from accept to trade messages with the client that connected but it's a copy of the file descriptor that was created in the parent process right.
My code is like this:
Code:
...
for (;;) {
if ((rem_socket=accept(loc_socket,&client_addr,&client_len))<0){
printf("server accept failure%d\n",errno);
perror("Server: ");
}
printf("\n%d\n",rem_socket);
pid = fork();
if (pid==0){
int choice;
data = shmat(shm_id, NULL, 0);
if (data == (char *)-1) {
printf("Could not attach to shared memory!\n");
exit(1);
}
/*1*/ showMenu(&rem_socket);
/*2*/ printf("%d\n",read (rem_socket,buf,BUFFER_SIZE));
printf("\n%s",buf);
choice = selection();
close(rem_socket);
exit(0);
}
}
...
wont there be problems? for instance when another clients tries to connect what happens? The parent process runs along with the child so won't it continue to accept (infinite loop) resulting in overwriting the rem_socket...
I haven't understood very clearly what exactly happens when fork is used with sockets and shared memory for starters I want some clarifying with the socket part and then I can move to shared memory and semaphores,
BTW Is it stupid and unnecessary to think about adding the sockets in the shared memory (although I have no idea right now if it's possible and how)