我正在处理的这项作业的一部分涉及一个通过套接字执行来自客户端的命令的程序。现在我唯一需要编辑的文件是 mathServer.c 我目前陷入了所提供说明中的几个部分中的其中一个:
完成方法 - doServer()。 doServer() 应该有一个循环,等待客户端连接到listenFd。当客户这样做时,它应该:
malloc() 为 2 个整数提供足够的内存
将来自accept()的文件描述符放入其中一个空格
将threadCount的值放入另一个空间,并递增 线程数
创建一个分离线程来处理这个新客户端。我将我的函数称为handleClient(),但您可以随意称呼您的函数。传递您的 malloc() 数组的地址。
然后循环应该返回另一个accept()。
这是我的 doServer:
void doServer (int listenFd)
{
// I. Application validity check:
// II. Server clients:
pthread_t threadId;
pthread_attr_t threadAttr;
int threadCount = 0;
// YOUR CODE HERE
int *a;
while(1) {
//1. If Malloc was NEVER (outside or inside loop) in this program then
// it outputs Thread 0 recieved
a = malloc(sizeof(int) * 2);
accept(getServerFileDescriptor(), NULL, NULL);
// 2.
a[0] = getServerFileDescriptor();
// 3.
a[1] = threadCount++;
// ALL 4
pthread_attr_init(&threadAttr);
pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
pthread_create(&threadId, &threadAttr, handleClient, &a);
pthread_join(threadId, NULL);
pthread_attr_destroy(&threadAttr);
}
}
这是我的handleClient方法:
void* handleClient(void* vPtr) {
// Use another pointer to cast back to int*
// Save the file descriptor and thread number in local vars
// free() the memory
// I wrote these 2 lines.
int *castMe = (int *)vPtr;
free(vPtr);
// II.B. Read command:
char buffer[BUFFER_LEN];
char command;
int fileNum;
int fd = castMe[0];
int threadNum = castMe[1];
char text[BUFFER_LEN];
int shouldContinue = 1;
while (shouldContinue)
{
text[0] = '\0';
read(fd,buffer,BUFFER_LEN);
printf("Thread %d received: %s\n",threadNum,buffer);
sscanf(buffer,"%c %d \"%[^\"]\"",&command,&fileNum,text);
//printf("Thread %d quitting.\n",threadNum);
return(NULL);
// YOUR CODE HERE
}
}
我发现,每当我删除 a = malloc(sizeof(int) * 2) 以及与 malloc 相关的所有内容时,它都会输出收到的线程 0。但是,当我保留 malloc 时,输出只是空白并且不会返回任何内容。
一开始我以为是因为我没有释放内存,但是内存是从handleClient释放的,对吗?
**请注意,这不是整个程序。你在这里看到的任何方法都是教授们的工作。这两种方法是我自己的(你的代码在这里)。假设教授的代码有效:) **
非常感谢任何帮助!
最佳答案
你的一段代码
// I wrote these 2 lines.
int *castMe = (int *)vPtr;
free(vPtr);
释放
由castMe
指向的内存,当您使用它时,您将取消引用无效内存
int fd = castMe[0]; //<----- BOOM
int threadNum = castMe[1];//<----- BOOM
此外,当您编写我删除了 = malloc(sizeof(int) * 2) 时,我猜您会按原样保留 a
声明
int *a;
即undefined behavior因为 a 没有指向有效的内存地址。
关于Malloc 的客户端/服务器问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42665506/