【发布时间】:2013-08-31 19:09:54
【问题描述】:
我是新来的。我有一个问题,我完全不知道是什么原因造成的! 我希望有人能帮助我。 我正在开发一个带有套接字的小型 TCP 服务器,它接收来自客户端的字符串并且必须在其上做一些事情。 程序在这个函数中一直被阻塞,永远不会返回:
int parse_request(char * request, char *start, char**headers, char *body)
函数的核心是2个嵌套strtok()的组合:
line = strtok_r (request, "\n", &saveptr1);
while (line != NULL) {
if (strcmp(line, "\r\n") == 0 || strcmp(line, "\r") == 0) bdy = 1;
else {
if (i == 1) {
/* the first line (command) */
printf("linea iniziale: ");
start = line;
start[strlen(line)] = '\0';
printf ("%s\n",start);
printf("\n");
}
else {
if (bdy == 0) {
/* the headers */
temp = line;
subline = strtok_r (temp, ":", &saveptr2);
head = subline;
head[strlen(subline)] = '\0';
subline = strtok_r (NULL, ":", &saveptr2);
if (subline != NULL) {
value = subline;
value[strlen(subline)] = '\0';
}
else value = "none";
if (strcmp(head, "Connection") == 0 && strcmp(value, "close") == 0) retval = 0;
if (strcmp(head, "Content-Length") == 0) ignoreboby = 0;
headers[j] = head;
headers[j+1] = value;
printf("header -> %s : %s\n", headers[j], headers[j+1]);
j = j + 2;
}
else {
headers[j] = '\0';
if (ignoreboby != 1){
/* the body */
printf("body: ");
body = line;
body[strlen(line)] = '\0';
printf ("%s\n",body);
}
else {
body = "\0";
**printf("body ignored\n");**
}
}
}
}
//printf("kkk");
line = strtok_r (NULL, "\n", &saveptr1);
i++;
}
程序在打印“body ignored”或“Body: %s\n, body”后立即阻塞。
有人有想法吗?我真的很麻烦! 谢谢
编辑:这可能是我创建和传递参数的方式是真正的问题吗?
char command[] = "\0", body[] = "\0";
char **headers;
headers = malloc(8192);
if (!headers) {
printf("Error in malloc()");
closesocket(s);
}
int x = parse_request(buf, command, headers, body);
【问题讨论】:
-
这与问题无关,但
body[strlen(line)] = '\0';形式的代码行不是必需的,因为它是当前编写的。 body 和 line 指向同一个内存,strlen 有效地返回了空终止符的位置,所以赋值没有影响(因为 body == line)。 -
你是对的!我删除了那些不必要的陈述。
-
如果您希望人们寻找的不仅仅是琐碎的语法问题,请发布SSCCE。就目前而言,这可能是非 NUL 终止的输入字符串的问题,或者您没有考虑的输入中可能有一些奇怪的东西。
-
通过您传递参数的方式,
command和body是函数的输入,对函数内部的本地start和body所做的更改将不会影响用于传递值的变量... -
伙计们,我要感谢大家的帮助。我找到了重点:我假设代码被阻止了,因为它停止打印他的输出,但现在我意识到问题出在 stdout 缓冲区!