C中的文件描述符分配 (File Descriptor Assignment in C)


問題描述

C中的文件描述符分配 (File Descriptor Assignment in C)

當在 C 中創建套接字或打開/創建文件時,分配給套接字/文件的文件描述符是否保證是可用的最低值描述符?C 規範在這方面對文件描述符分配有什麼看法?


參考解法

方法 1:

It's not guaranteed to be the lowest, and is implementation dependent (1). In general, however, the routine that assigns open file descriptors uses a method that gives you the first open on. It could be that immediately after several lower ones free, leaving you with a higher descriptor than you might expect though.

The only reason I can think of to know this, though, is for the select function, which is sped up if you pass it the highest file descriptor you need to check for.

(1) Note that those implementations that follow the IEEE standard do guarantee the lowest unused descriptor for files, but this may not apply to sockets. Not every implementation follows the IEEE standard for open(), so if you're writing portable software it is best not to depend on it.

方法 2:

I don't think you'll find it in the C spec, more likely the spec for your OS. My experience in Linux has been that it's always the lowest.

方法 3:

I'll counter this with another question ‑ why does this matter? You shouldn't be comparing the file descriptor with anything (unless checking for stdin/stdout/stderr) or doing math with it. As long as it fits in an int (and its guaranteed to) that's all you really need to know.

方法 4:

Steve M is right; C has no notion of sockets, and its file I/O functions use a [pointer to a] FILE object, not a descriptor.

方法 5:

<p>@aib the open(), close(), lseek(), read(), write() all make use of file descriptors. I hardly ever use streams for I/O.</p>

<p>@Kyle it matters because of statements like select(). Knowing the highest descriptor can improve performance.</p>

(by Kevin PAdam DavisSteve MKyle CroninaibKevin P)

參考文件

  1. File Descriptor Assignment in C (CC BY‑SA 2.5/3.0/4.0)

#file-descriptor #C






相關問題

在 Android 中持久化文件描述符 (Persisting File Descriptors in Android)

無法理解 select() 系統調用 (failure to understand select() system call)

文件描述符中實際存儲了多少信息? (How much information is actually stored in a file descriptor?)

為同一個文件描述符創建兩個文件是否定義明確? (Is creating two FILEs for the same file descriptor well-defined?)

Android文件描述符洩漏調試 (Android file descriptor leakage debuging)

C中的文件描述符分配 (File Descriptor Assignment in C)

在某些 linux 程序中關閉奇怪的描述符 (Strange descriptor closing in some linux programs)

c read() 導致錯誤的文件描述符錯誤 (c read() causing bad file descriptor error)

C中系統調用的文件句柄問題 (Filehandle issue with system call in C)

使用 copy_file_range 進行複制加速 (Copy acceleration with copy_file_range)

打開文件過多錯誤,但 99.5% 的 inode 是免費的 (Too many open files error but 99.5% inodes are free)

SIGPIPE 由於文件描述符和進程替換 (SIGPIPE due to file descriptors and process substitution)







留言討論