C UDP read和recv破坏了我的代码

时间:2017-12-20 00:21:37

标签: c sockets udp recvfrom

所以我正在使用UDP套接字和poll(),试图能够同时等待连接和读取输入,但我想出了最奇怪的错误,我不知道如何处理它。这是我的代码中导致问题的部分。

int n=1;   //set n =1 so that it can enter first loop

while (1) {
  for(int j = 0; j < 2; j++){
    printf("loop1\n");
    if(n>0){
      printf("loop2\n");
      mlen = read(sd, buf, BSIZE);      
      //I would like to use read here, but I've tried both read and recvfrom
      //and both have the same issue \/ that's the other code I was trying
      //mlen = recvfrom(sd,buf,BSIZE,0,(struct sockaddr *)&cad, &fromlen);
      if(mlen<0){
        perror("recvfrom");
        exit(1);
      }

      /* more code here that does stuff with buffer info */
    }
    else {
      perror("poll");
      exit(1);}
    }
  }
  n = poll(pollarr,2,-1);
  printf("now n is %d\n", n);
}

所以这就是奇怪的地方。当我运行此代码时,它打印出loop1,但不打印loop2,即使我在开头明确设置n = 1。我将loop1 print语句更改为“printf(”现在n是%d \ n“,n);”看看发生了什么,然后根本没有打印任何东西。

为了增加这个谜团,无论我是否使用read或recv,都会发生这种情况,但是当我注释掉这两个代码时,我的代码就进入了两个循环就好了。

因此,无论如何,read和recv都会阻止我的程序按照它应该的方式运行,甚至在达到这些行之前。我不知道可能会发生什么,我最好的猜测是,这是一些我不知道的晦涩的C事物。有谁知道出了什么问题?

如果重要,我想我正在使用Linux。

0 个答案:

没有答案
相关问题