[英]Using sockets in multithread server
伙計們!
我正在* nix下的c上開發多線程服務器。 在該過程的主線程中,我有一個監聽套接字,它在等待連接(接受)。 當它獲得連接時(接受返回客戶端套接字描述符),我用一些例程啟動新的pthread,該例程將響應請求並關閉客戶端套接字描述符。 它看起來像這樣:
while(1)
{
sock_cl =(int *)malloc(sizeof(int));
*sock_cl = accept(sock_serv, NULL, NULL);
pthread_create(thread, attr, answer, sock_cl);
}
回答功能:
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;
}
在答案功能中,我調用recv以從客戶端獲取數據並發送一些答案。 它在Linux系統(Arch,Debian,Ubuntu)上運行良好,但是當我嘗試在Unix(Solaris)下運行時,recv函數卻出現了細分。 問題不在緩沖區中,因為如果我嘗試在與答案函數相同的線程中調用答案函數,那么我就不會出現細分問題。 因此,將套接字與pthreads一起使用存在一些問題。
請給我建議任何解決方案如何在多線程服務器中使用套接字。 感謝您將來的回答!
在Solaris上,通常需要使用-mt
進行編譯,以正確地編譯和鏈接多線程程序。 如果不使用它,則會在線程中隨機崩潰,如您所見。
我認為在unix recv函數中失敗,並且分段不准確是由於代碼段free(args);
可能這可能是原因
close(sock_cl);
free(arg);
return NULL;
該sock_cl在線程之間共享,並且由於沒有同步應答功能,並且由於釋放了該指針,其他線程肯定會崩潰,因此如果可能,可以通過在valgrind中運行該程序來檢查是否損壞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.