Is there a system call or some way to know the type of file descriptor in Linux (e.g. regular file fd, socket fd, signal fd, timer fd)?

asinix :

As I keep discovering, there are a variety of File Descriptors - Almost every thing is abstracted around a file descriptor: regular files, sockets, signals and timers (for example). All file descriptors are merely integers.

Given a file descriptor, is it possible to know what type it is? For example, it would be nice to have a system call such as getFdType(fd).

If an epoll_wait is awakened due to multiple file descriptors getting ready, the processing of each file descriptor will be based upon its type. That is the reason I need the type.

Of course, I can maintain this info separately myself but it would be more convenient to have the system support it.

Also, are all file descriptors, irrespective of the type, sequential. I mean if you open a regular data file, then create a timer file descriptor, then a signal file descriptor, are they all guaranteed to be numbered sequentially?

Nate Eldredge :

As "that other guy" mentioned, the most obvious such call is fstat. The st_mode member contains bits to distinguish between regular files, devices, sockets, pipes, etc.

But in practice, you will almost certainly need to keep track yourself of which fd is which. Knowing it's a regular file doesn't help too much when you have several different regular files open. So since you have to maintain this information somewhere in your code anyway, then referring back to that record would seem to be the most robust way to go.

(It's also going to be much faster to check some variables within your program than to make one or several additional system calls.)

Also, are all file descriptors, irrespective of the type, sequential. I mean if you open a regular data file, then create a timer file descriptor, then a signal file descriptor, are they all guaranteed to be numbered sequentially?

Not really.

As far as I know, calls that create a new fd will always return the lowest-numbered available fd. There are old programs that rely on this behavior; before dup2 existed, I believe the accepted way to move standard input to a new file was was close(0); open("myfile", ...);.

However, it's hard to really be sure what fds are available. For example, the user may have run your program as /usr/bin/prog 5>/some/file/somewhere and then it will appear that fd 5 gets skipped, because /some/file/somewhere is already open on fd 5. As such, if you open a bunch of files in succession, you cannot really be sure that you will get sequential fds, unless you have just closed all those fds yourself and are sure that all lower-numbered fds are already in use. And doing that seems much more of a hassle (and a source of potential problems) than just keeping track of the fds in the first place.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8632&siteId=1