命名为管道错误

时间:2016-12-03 21:05:00

标签: c pipe named

对不起的头衔很抱歉,我没有'知道如何解释这个。 我有2个程序:服务器和客户端。 服务器创建一个命名管道并等待读取内容。客户端连接并向管道发送消息。服务器检查消息的一部分以获得"类型"消息(在这种情况下,键入是" HELO")读取发送字符串的char 4到8。如果我发送" HELO",服务器打印"键入:HELO"正如所料。 但是,如果我发送一条带有别的东西的消息,它就不会打印出来#34;不匹配"正如所料:它什么也没做。 这是代码:

#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以外的其他内容时,它不打印&#34;不匹配&#34;但后来我发送HELO并打印出来:&#34;没有匹配类型:HELO&#34;,就好像第一个&#34;不匹配&#34;卡在管道中而不是立即打印,我不明白为什么。

1 个答案:

答案 0 :(得分:0)

  

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

no match确实卡在某种方式,但不是在管道中,而是在标准输出流的服务器缓冲区中,大概是行缓冲< / em>,我。例如,当遇到换行符时字符(打印) 。要解决此问题,只需将printf("no match")更改为printf("no match\n")puts("no match")