Hi everyone, I have a problem and I'm really out of my depth with this one.
Basically I have created a client/server architecture in C for the first time, and after a couple of days, I have finally got it bug free and up and running cleanly. I have connected one client and updated the variables on the server without any problems; my problem, however, arised when a second client connects. Now although this second connection works ok, the variables are not shared between this first and second connection due to the fact that I have created a new thread for the server using fork(). Is there any way around this by using a shared memory space, or utilising some part of the network package. Any help would be greatly appreciated.
This is the current code I am using to initialize the server:
Code:
int main(int argc, char *argv[])
{
int newsockfd, sockfd ; /* File descriptors */
int portno; /* Port number */
int clilen; /* Size of address of the client */
pid_t pid; /* PID for child processes */
struct sockaddr_in serv_addr, cli_addr; /* Contains internet address */
if (argc < 2) {
fprintf(stderr, "ERROR: no port number provided.\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0); /* Creates a new socket, internet
domain, TCP */
bzero((char *) &serv_addr, sizeof(serv_addr)); /* Sets buffer to zero */
portno = atoi(argv[1]); /* Gets the port number */
serv_addr.sin_family = AF_INET; /* Sets address family */
serv_addr.sin_port = htons(portno); /* Sets the port number */
serv_addr.sin_addr.s_addr = INADDR_ANY; /* Sets IP of server */
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR: cannot bind\n"); /* Binds a socket to the address that the
server is running on */
listen(sockfd, 5); /* Allows process to listen on the socket for connections,
sets the number of connections that can be waiting
while the process is handling a particular connection */
clilen = sizeof(cli_addr);
testInit(); /* Initialises the server variables*/
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
/* Causes process block until connection is started - returns a new file
descriptor */
if (newsockfd <0)
error("ERROR: on accept\n");
printf("Client has connected\n");
pid = fork(); /* Creates a new thread to listen for other connections */
if (pid < 0)
error("ERROR: on fork\n");
if (pid == 0) {
close(sockfd);
runUpdate(newsockfd);
exit(0);
}
else close (newsockfd);
}
/* end while */
return 0;
}