[英]A function with C strings that never return
我是新來的。 我有一個問題,我絕對不知道是什么原因造成的! 我希望有人可以幫助我。 我正在開發一個帶有套接字的小型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++;
}
該程序在打印“忽略的正文”或“正文:%s \\ n,正文”之后立即阻塞。
有人有主意嗎? 我真的很麻煩! 謝謝
編輯:這可能是我創建並傳遞參數的真正問題的方法嗎?
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);
那是因為您不更改line
因此陷入了while
循環中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.