Linux how to check whether the file descriptor is released

     Because everything is a file in Linux programming, such as sockets, text files, db, flash, etc., especially sockets on the server side in network programming, after three handshake, they often forget to deal with sockets, which eventually leads to the file descriptor consumption of the entire process Exhausted; in Linux writing programs often encounter fd forget to close the situation, there will also be file descriptor exhaustion, the following means can help you check whether the file descriptor has forgotten to close.

 

1) Under Linux system, the maximum number of FDs allowed to be opened by all processes. check sentence:

/ proc / sys / fs / file-max
2) Under Linux system, the number of fds that have been opened by all processes and the maximum number allowed. check sentence:

         [root@localhost logs]# cat /proc/sys/fs/file-nr

 

2112   0  2100000
Number of file handles allocated  Number of file handles used Maximum number of file handles 

 

 

 

The number of allocated file handles: If you forget to close the file descriptor, this value will continue to increase, so pay special attention to this situation when doing stress tests.

 

Use c language to get

       

#include <stdio.h>

typedef struct        
{
    unsigned int assigned;/*已分配文件句柄的数目    */      
    unsigned int used;/*文件句柄的最大数目*/ 
    unsigned int total;/*文件句柄的最大数目*/                       
}system_info_fd_t;

static void ptcp_server_get_sys_fd_info(system_info_fd_t *info_fd) 
{
    FILE *fd;          
    char buff[256];   
    fd = fopen ("/proc/sys/fs/file-nr", "r"); 
    fgets (buff, sizeof(buff), fd); 
    sscanf (buff, "%u    %u    %u", &info_fd->assigned, &info_fd->used,&info_fd->total); 
    fclose(fd);    
}

3) The maximum number of FDs allowed to be opened by a single process. Query statement:

ulimit -n
4) A single process (for example, through ps -aux to see that the process id of interest is 655) has opened fd.

ls -l / proc / 655 / fd / | wc -l can see that fd keeps increasing, so that you can confirm that the process has forgotten to close the file description

 

 

78 original articles published · 32 praised · 120,000 views

Guess you like

Origin blog.csdn.net/caofengtao1314/article/details/104799259