File descriptor constant

I have a requirement to close all the file descriptors from 3 to 1024 for a particular application.

Right now, this is how I do it ..

for ( int i = 3 ; i <= 1024; ++i )
close(i);

The change I am looking at is, I want to do away with the number 1024 and replace it with a constant which might be present in some header file. I need the name of the constant and the header file.

I tried looking into /usr/include/limits.h and /usr/include/ulimit.h

Did find anything I was looking for.

I am not looking for a

#define MAX_FILE_DESCRIPTORS 1024

either; i.e. the number should not depend on the user. Should be a system constant.

Any help appreciated.

Vino

That's not the way it works. It is, potentially, per process. You can call getrlimit to obtain the value.

Using getrlimit and the appropriate constants, this is what I am using now.

struct rlimit RL;

getrlimit(RLIMIT_NOFILE, &RL)
  for ( int fd = 3; fd <= RL.rlim_cur; ++fd )
   close(fd);

Apparently rlim_cur and rlim_max gives me 1024 on my machine.

Thanks,
Vino

You misunderstand. A process can call setrlimit() and reduce the number of open file desriptors allowed by the process. Or it can be reduced for all users.

The kernel on some versions of unix can be reconfigured to allow more than 1024 open file descriptors.

The point: You cannot depend on 1024

Jim,

I agree with you. And that is why, I took to getrlimit.

When I said

Apparently rlim_cur and rlim_max gives me 1024 on my machine.

I was just giving away information which was needed.

Vino