gpt4 book ai didi

c - 命名管道错误

转载 作者:行者123 更新时间:2023-11-30 16:53:15 24 4
gpt4 key购买 nike

抱歉,标题不好,我不知道如何简单地解释这一点。我有 2 个程序:服务器和客户端。服务器创建一个命名管道并等待读取某些内容。客户端连接并向管道发送消息。服务器检查消息的一部分以获取消息的“类型”(在本例中,类型为“HELO”),读取发送字符串的字符 4 到 8。如果我发送“HELO”,服务器将按预期打印“类型:HELO”。但是,如果我发送带有其他内容的消息,它不会按预期打印“不匹配”:它什么也不做。这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#define BUF_SIZE 256

char * getType(char * message){
char* type = malloc(sizeof(char)*5);
memcpy(type,&message[4],4);
type[4] = '\0';
return type;
}

int main(int argc, char* argv[]){

mkfifo("tchatserv", 0666);
int fd = open("tchatserv", O_RDONLY);
char buf[BUF_SIZE];
int val;
while(1){
val = read(fd, buf , BUF_SIZE );
if(val >0){
char * type = getType(buf);
if(strcmp("HELO",type) == 0){
printf("Type: %s\n", type);
}
else{
printf("no match");
}
}
}
}

这是客户:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>

char * makeInt(int val){
char* res = malloc(sizeof(char)*5);
char l [5] = "";
sprintf(l,"%d",val);
if(val < 10){
strcat(res,"000");
strcat(res,l);
}
else if(val < 100){
strcat(res,"00");
strcat(res,l);
}
else if(val < 1000){
strcat(res,"0");
strcat(res,l);
}
else if( val < 10000){
strcat(res,l);
}
return res;
}

char * makeString(char * ch, int final){
int t = strlen(ch);
if(final == 1){
t = t+4;
}
char * chaine = makeInt(t);
strcat(chaine,ch);
return chaine;
}
void connection(){

printf("Pseudo:\n");
char * pseudo = malloc(sizeof(char)*30);
pseudo[0] = '\0';
scanf("%s", pseudo);

printf("Tube:\n");
char * tube = malloc(sizeof(char)*30);
tube[0] = '\0';
scanf("%s", tube);

char * message = malloc(sizeof(char)*100);
char * type = "HELO";
message[0] = '\0';
strcat(message,type);
pseudo = makeString(pseudo,0);
strcat(message,pseudo);
tube = makeString(tube,0);
strcat(message,tube);
message = makeString(message,1);
printf("%s",message);
int fd = open("tchatserv", O_WRONLY);
write(fd,message,256);
}
int main(int argc, char* argv[]){
connection();
return 0;
}

编辑:当我尝试发送除 HELO 之外的其他内容时,它不会打印“不匹配”,但随后我发送 HELO 并打印:“不匹配类型:HELO”,就像第一个“不匹配”卡住一样在管道中而不是立即打印,我不明白为什么。

最佳答案

When i try to send something else than HELO it doesn't print "no match" but then i send HELO and it prints : "no match Type: HELO", like if the first "no match" got stuck in the pipe instead of getting printed immediately, i don't understand why.

不匹配确实在某种程度上被卡住了,虽然不是在管道中,而是在标准输出流的服务器缓冲区中,大概是>行缓冲,i。例如,当遇到换行符时,会传输字符(打印)。要解决此问题,只需将 printf("no match") 更改为 printf("no match\n")puts("no match").

关于c - 命名管道错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40952487/

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