使用close()套接字(C++)的错误文件描述符

问题描述:

当我的程序无法连接其他主机时,我的文件描述符用完了。 close()系统调用不起作用,打开套接字的数量增加。我本身它使用close()套接字(C++)的错误文件描述符

执行cat/proc/SYS/FS /文件-NR

从控制台打印:

连接:没有到主机的路由

接近:错误的文件描述符

连接:没有路由到主机

接近:坏的文件描述符

..

代码:

#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; 
} 

修复:

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

    else 
    write_to_server (sock); 

    if (close (sock) != 0) 
    perror("close"); 

看起来问题出在你的程序的结构。每次通过无限循环,您都在创建一个新的套接字。我建议将其移出循环并重新使用它。

如果您想立即修复您现在正在执行的操作,请在现在使用的“连接”失败if语句中使用close。描述符由“套接字”呼叫分配,并且只与“连接”呼叫连接。通过设置你的'sock'变量为-1,你扔掉'socket'分配的描述符。致电关闭,然后将其设置为-1,您应该设置。

+0

+1:即使连接失败,仍然需要关闭套接字而不是扔掉手柄。 – 2010-04-20 12:45:35

+0

thx问题修复 – user321246 2010-04-20 15:59:26