I have a client/server program in which I am trying to use multithreading on the server side. I would like the server to take create a master socket and then listen on this socket until a incoming connection comes in. When this happens I create a thread that handles the request while the main resumes listening for more connections coming in. However, when I try implement this my server successfully creates the thread and calls the appropriate functions and then responds on the socket passed in the struct to the thread. But for some reason the client never receives this data and is stuck waiting for the server's response. Is there an error which I have when passing my socket or I'm not really sure what is wrong. Thanks and here is a copy of what I have:
Code:
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include "http.h"
#include "myTCP.h"
void *runner( void * ptr);
struct parm{
int socket;
char path[100];
char *from;
char *userAgent;
};
int main(int argc, char *argv[]) {
int port=-999; /* port number to connect to, on server */
int msock=-999; /* socket descriptor for connection */
int iRet; //Return value for pthread_create
int pid;
struct parm *p;
pthread_t aThread; //Thread to be executed
p=(struct parm *)malloc(sizeof(struct parm)); //Allocate space for the p structure
pid = getpid();
if(argc==1) {
p->userAgent = argv[0];
port = WL_PORT;
} else if(argc==2) {
p->userAgent = argv[0];
if(atoi(argv[1]) >1024) {
port = atoi(argv[1]);
}
else {
port = WL_PORT;
}
} else {
fprintf(stderr,"ERROR: useage: <%s> <path> [<port>]\n", argv[0]);
exit(1);
}
#ifdef DEBUG
fprintf(stderr,"DEBUG: %d %s will listen on port %d\n", pid, argv[0], port);
#endif
msock = myTCPserverSocket(port, argv[0]);
/*
* Now accept connections and service clients forever,
*/
while(1) {
/*Accept the client's socket*/
p->socket = myTCPaccept(msock, argv[0]);
iRet = pthread_create(&aThread, NULL, runner, (void *) p);
pthread_join(aThread, NULL);
}
}
void *runner( void *arg) {
int sleepTime =0;
int serverGet=-999; /*Return value for the myHTTPserverGet function*/
int serverResp=-999; /*Return value for the myHTTPserverResponse function*/
struct parm *p = (void *) arg;
//Get the client's request
if((serverGet = myHTTPserverGet(p->socket, p->path, p->from, p->userAgent, &sleepTime)) < 0) {
fprintf(stdout, "Trouble in myHTTPserverGet.\nReturn Value = %d\n", serverGet);
exit(1);
}
//sleep(sleepTime);
//Respond to the Client
if((serverResp =myHTTPserverResponse(p->socket, p->userAgent, serverGet, p->path, sleepTime)) < 0) {
fprintf(stdout, "Trouble in myHTTPserverResponse.\nReturn Value = %d\n", serverResp);
exit(1);
}
pthread_exit(0);
}