gpt4 book ai didi

c - 在多线程服务器中使用套接字

转载 作者:行者123 更新时间:2023-11-30 17:51:49 24 4
gpt4 key购买 nike

伙计们!

我正在 *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 中使用套接字存在一些问题。

请告诉我如何在多线程服务器中使用套接字的任何解决方案。感谢您 future 的回答!

最佳答案

在Solaris上,通常需要使用-mt进行编译才能正确编译和链接多线程程序。如果您不使用它,您将在线程中遇到随机崩溃,就像您所看到的那样。

关于c - 在多线程服务器中使用套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16508466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com