cstdioresource-leak

How to close files that are opened in an external function


I am using a pre-compiled C library function (while coding myself in C++) which opens a file without closing it. I confirmed this by looking at the process's file descriptor list in /proc/{PID}/fd. Each time i call the function, a file descriptor pointing the same file is created.

My problem is that i have to do a huge amount of iterations over that function and it eventually crashes because of that.

Of course, i have no pointer on the file stream so i can not use fclose.

I tried using fcloseall() but it does not close any of the streams that are open.

Here is some minimal code:


#include <stdio.h>
const int MAX_ITERATIONS = 10000;
for(int i = 0; i < MAX_ITERATIONS ; i++){
   result = Call(...);
   int closed = fcloseall();
}

here, closed is allways equal to 0 and the number of file descriptors never diminishes.

Is there another way of forcing those file streams to be closed or do i need to completely stop the program in order to destroy them?


Solution

  • You can try manually closing those file descriptors:

    int fd, next_fd, next_fd2;
    next_fd = dup(STDIN_FILENO);
    close(next_fd);
    
    // call that function which forgets to close its file descriptors
    
    next_fd2 = dup(STDIN_FILENO);
    close(next_fd2);
    for(fd = next_fd; fd < next_fd2; ++fd)
        close(fd);
    

    Note that this method is not thread-safe because it may close file descriptors opened by other threads.