为什么这样的结构包含两个仅包含一个元素的数组字段? [英] Why does such a struct contain two array fields containing only one element?
问题描述
请注意:此问题不是重复的内容(一个struct中的元素数组)
以下代码摘自Linux内核源代码(版本:3.14)
struct files_struct
{
atomic_t count;
struct fdtable __rcu *fdt;
struct fdtable fdtab;
spinlock_t file_lock ____cacheline_aligned_in_smp;
int next_fd;
unsigned long close_on_exec_init[1];
unsigned long open_fds_init[1];
struct file __rcu * fd_array[NR_OPEN_DEFAULT];
};
我只是想知道为什么将close_on_exec_init
和open_fds_init
定义为包含一个元素的数组,而不是仅仅将其定义为unsigned long close_on_exec_init;
和unsigned long open_fds_init;
.
这些字段是一种优化,因此Linux不必为不超过BITS_PER_LONG
打开文件描述符的典型进程执行尽可能多的分配. /p>
close_on_exec_init
字段为分配了files_struct
的fdt->close_on_exec
提供初始存储. (请参阅fs/file.c
中的dup_fd
.)
如果相应的文件描述符已设置"close-on-exec"标志,则设置fdt->close_on_exec
的每个位.因此,如果进程具有比unsigned long
中的位数更多的打开文件描述符,则Linux仅需要为fdt->close_on_exec
分配额外的空间.
open_fds_init
字段与fdt->open_fds
字段具有相同的功能. fd_array
字段与fdt->fd
字段具有相同的功能. (请注意,fd_array
的大小为BITS_PER_LONG
.)
close_on_exec_init
和open_fds_init
字段以前的类型为struct embedded_fd_set
,但在此提交.提交消息没有解释为什么作者选择使用单元素数组而不是纯标量.也许作者(David Howells)只是想避免使用&
运算符.
Please Note: This question is not a duplicate of ( One element array in struct )
The following code is excerpted from the Linux kernel source (version: 3.14)
struct files_struct
{
atomic_t count;
struct fdtable __rcu *fdt;
struct fdtable fdtab;
spinlock_t file_lock ____cacheline_aligned_in_smp;
int next_fd;
unsigned long close_on_exec_init[1];
unsigned long open_fds_init[1];
struct file __rcu * fd_array[NR_OPEN_DEFAULT];
};
I just wonder why close_on_exec_init
and open_fds_init
are defined as arrays containing one element, rather than just defined as unsigned long close_on_exec_init;
and unsigned long open_fds_init;
.
These fields are an optimization so Linux doesn't have to perform as many allocations for a typical process that has no more than BITS_PER_LONG
open file descriptors.
The close_on_exec_init
field provides the initial storage for fdt->close_on_exec
when a files_struct
is allocated. (See dup_fd
in fs/file.c
.)
Each bit of fdt->close_on_exec
is set if the corresponding file descriptor has the "close-on-exec" flag set. Thus Linux only needs to allocate additional space for fdt->close_on_exec
if the process has more open file descriptors than the number of bits in an unsigned long
.
The open_fds_init
field serves the same function for the fdt->open_fds
field. The fd_array
field serves the same function for the fdt->fd
field. (Note that fd_array
has a size of BITS_PER_LONG
.)
The close_on_exec_init
and open_fds_init
fields formerly had type struct embedded_fd_set
, but were changed to bare arrays in this commit. The commit message doesn't explain why the author chose to use one-element arrays instead of bare scalars. Perhaps the author (David Howells) simply wanted to avoid using the &
operator.
这篇关于为什么这样的结构包含两个仅包含一个元素的数组字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!