I have developed a server in C ++ and a client that connects to it.
Both are run on a PC with linux.
When we run the server and a client is connected to it, a
Segmentation fault on the server, specifically, on the line:
sClient = ((struct ThreadArgs *) threadArgs) -> sClient;
As someone on the other site said, you need to make ServerTCP::ThreadMain() static. Remember, non static member functions have an extra hidden parameter (the "this" pointer), so there are really two parameters to ThreadMain(): "this" and "threadArgs". By passing it to pthread_create, you're causing it to be called with just one parameter.
If you don't believe me, try adding this to the beginning of ThreadMain(): printf("this=%p. ThreadArgs=%p\n", this, threadArgs);
I'm nearly certain that you'll find that the pointers are the same.
If threadMain really must be a normal member then you'll need a glue function to call it. The code below is untested:
// Parameter block for the threadMain() function
struct ThreadParams {
ThreadParams(int f, ServerTCP *s) :
sClient(f), server(s) {}
int sClient;
ServerTCP *server;
};
void *ServerTCP::threadMain(int sClient) // Change this to take sClient directly
{
...
}
// static function, not a member of any class. This unpacks the params, calls
// ServerTCP::ThreadMain() and deletes the parameter block.
staticvoid *threadMain(void *arg)
{
ThreadParams *params = (ThreadParams*)arg;
return params->ThreadMain(params->sClient);
delete(params);
}
...
void ServerTCP::waitConnections()
{
...
ThreadParams *params = new ThreadParams(sClient, this);
// threadMain takes ownership of params.
if (pthread_create(&threadID, NULL, threadMain, params) != 0) ...
}