It depends on what the code is legitimately trying to do, but you could do it with setrlimit() RLIMIT_NOFILE .
Something like this should work:
#include <sys/resource.h> struct scoped_fd_blocker { rlim_t prev; scoped_fd_blocker() { rlimit lim; getrlimit(RLIMIT_NOFILE, &lim); // get the current limit prev = lim.rlim_cur; // save old limit lim.rlim_cur = 0; // set the soft limit to 0 setrlimit(RLIMIT_NOFILE, &lim); // do the set } ~scoped_fd_blocker() { rlimit lim; getrlimit(RLIMIT_NOFILE, &lim); // get the current limit lim.rlim_cur = prev; // reset the soft limit to the previous value setrlimit(RLIMIT_NOFILE, &lim); // do the set } }; // Example Usage: void do_stuff() { scoped_fd_blocker blocker; Application->DoImportantOperation(); }
Basically, this means that the OS does not allow your process to open any file descriptor, even if the existing one is closed, by resetting the descriptor limit of the open open process file. Please note that these are more than just files and may have some unforeseen consequences. This will include files, sockets, event objects, directories, shared resources, channels, and will also prevent C file libraries from opening. (Some C libraries use file locks and more to control concurrency.) Think of all the things that open files (like dlopen ).
Any attempt to open the file descriptor will fail (return -1), and errno will be set to EMFILE , which translates as "Error 24: Too many open files."
I put all this in a structure so that it is safe.
source share