Domanda

Sono a corto di descrittori di file quando il mio programma non può collegare un altro host. La chiamata di sistema close () non funziona, il numero di prese aumenta aperte. Posso SE con

  

cat / proc / sys / fs / file-nr

Stampa dalla console:

  

connect: No route to host

     

close: Bad descrittore di file

     

connect: No route to host

     

close: Bad descrittore di file

     

..

Codice:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <iostream>
using namespace std;

#define PORT            1238
#define MESSAGE         "Yow!!! Are we having fun yet?!?"
#define SERVERHOST      "192.168.9.101"

void
write_to_server (int filedes)
{
  int nbytes;

  nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1);
  if (nbytes < 0)
    {
      perror ("write");
    }
}

void
init_sockaddr (struct sockaddr_in *name,
               const char *hostname,
               uint16_t port)
{
  struct hostent *hostinfo;

  name->sin_family = AF_INET;
  name->sin_port = htons (port);
  hostinfo = gethostbyname (hostname);
  if (hostinfo == NULL)
    {
      fprintf (stderr, "Unknown host %s.\n", hostname);
    }
  name->sin_addr = *(struct in_addr *) hostinfo->h_addr;
}

int main() 
{
 for (;;)
 {
  sleep(1);
  int sock;
  struct sockaddr_in servername;

  /* Create the socket. */
  sock = socket (PF_INET, SOCK_STREAM, 0);
  if (sock < 0)
  {
   perror ("socket (client)");
  }

  /* Connect to the server. */
  init_sockaddr (&servername, SERVERHOST, PORT);
  if (0 > connect (sock,
    (struct sockaddr *) &servername,
    sizeof (servername)))
  {
   perror ("connect");
   sock = -1;
  }

  /* Send data to the server. */
  if (sock > -1)
   write_to_server (sock);
  if (close (sock) != 0)
   perror("close");
 }
return 0;
}

Fix:

  if (0 > connect (sock,
    (struct sockaddr *) &servername,
    sizeof (servername)))
  {
   perror ("connect");
  }

  else
   write_to_server (sock);

  if (close (sock) != 0)
   perror("close");
È stato utile?

Soluzione

Sembra che il problema è nella struttura del programma. Ogni volta che attraverso il vostro ciclo infinito, si sta creando un nuovo socket. Io suggerirei spostare questo fuori dal giro e ri-utilizzarlo.

Se vuoi risolvere solo il modo in cui si sta facendo ora, però, l'uso vicino all'interno del "Connect" falliti if che hai ora. Il descrittore è assegnato dalla chiamata 'presa' e solo collegato con la chiamata 'connect'. Impostando la variabile 'calza' a -1, si sta gettando via il descrittore assegnato da 'presa'. Invito a chiudere, poi impostato a -1 e si dovrebbe essere impostato.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top