
Question:
guys!
I'm developing multithread server on c under *nix. In the main thread of the process I have listening socket which waits for connections (accept). When it gets a connection (accept returns client socket descriptor) I start new pthread whith some routine, which answers the request and closes client socket descriptor. It looking something like this:
while(1)
{
sock_cl =(int *)malloc(sizeof(int));
*sock_cl = accept(sock_serv, NULL, NULL);
pthread_create(thread, attr, answer, sock_cl);
}
answer function:
void *answer(void *arg)
{
int sock_cl;
char *buf;
ssize_t r;
lsres_t *ans;
char *path;
char status[STATUS_SIZE];
sock_cl = *((int *)arg);
if((buf = (char *)malloc(BUF_SIZE + 1)) == NULL)
{
sprintf(status, "%i\n", -1);
send_data(sock_cl, status, STATUS_SIZE);
close(sock_cl);
free(arg);
return NULL;
}
memset(buf, '\0', BUF_SIZE + 1);
if((r = recv(sock_cl, buf, BUF_SIZE, 0)) <= 0)
{
close(sock_cl);
free(arg);
return NULL;
}
path = strtok(buf, "\r\0");
if((ans = lscreate()) == NULL)
{
sprintf(status, "%i\n", -1);
send_data(sock_cl, status, STATUS_SIZE);
}
else
{
if(myls(path, ans) != 0)
{
sprintf(status, "%i\n", -1);
send_data(sock_cl, status, STATUS_SIZE);
}
else
{
sprintf(status, "%i\n", ans->status);
send_data(sock_cl, status, STATUS_SIZE);
send_data(sock_cl, ans->buf, ans->written_size);
}
lsdestroy(ans);
}
close(sock_cl);
free(arg);
return NULL;
}
In answer function I call recv to recive data from client and send some answer. It works fine under Linux systems (Arch, Debian, Ubuntu), but when I try to run it under Unix (Solaris), I get a Segmentation fall in recv function. The problem is not in buffer, because if i try to call answer function in the same thread as answer function, I have no Segmentation fall. So there is some issue in using sockets with pthreads.
Please, advice me any solution how to use sockets in multithread server. Thank's for the future answers!
Answer1:On Solaris, you generally need to compile with -mt
to correctly compile and link a multithreaded program. If you don't use it, you'll get random crashes in threads like you see.
I think in unix recv function fails and the segmentation faut is due to the code segment free(args);
May be this could be the reason
close(sock_cl);
free(arg);
return NULL;
This sock_cl is shared among threads and because there is no synchronization for the answer function and because you are freeing this pointer other threads bound to crash, if possible you check this same program in by running in valgrind for corruption.