Hi I have built a simple web server in C, and I now have to make it multi threaded. I also have to produce a multi threaded command line client to test the multi-threaded capability of the server. I have finished the client and the server however I get read errors when making more than 1 request to the server. I believe it is because I need to look some resources with mutexes but I'm not quite sure how and where to do it.
Code:
while (1) {
//Accept new connection and fork
remote_len = sizeof(remote_addr);
sd = accept(lsd, (struct sockaddr *) &remote_addr, &remote_len);
printf("Connection Received!\n");
//Store remote IP in "inetadddr" for error logging
inet_ntop(AF_INET, &(remote_addr.sin_addr), inetaddr, INET_ADDRSTRLEN);
if (sd < 0) {
logerrors("Socket Error: Cannot accept connection from",inetaddr);
}
params->sd = sd;
params->inetaddr = inetaddr;
threadr = pthread_create(&thread[i++], NULL, web, (void*) params);
That is the accept code in main and the new thread starts with web function:
Code:
void *web (void *arg)
{
int n, sd;
char buffer[BUFFERSIZE];
char *inetaddr;
struct funcparams *params = (void *) arg;
sd = params->sd;
inetaddr = params->inetaddr;
bzero(buffer, BUFFERSIZE);
//Read browser request
n = read(sd,buffer,BUFFERSIZE);
So this read request fails, well it works for the first connection then fails on the rest. Like I said i'm sure its because I need to lock the resources sd and inetaddr but i'm not sure where to lock and unlock. Any help would be greatly appreciated