英文:
integer flags in system function calls
问题
以下是您要翻译的内容:
这是一个我所指的示例:
```c
int open(const char *pathname, int flags);
我对将int
用作设置特定位的方式感到好奇,因为我曾认为最“可移植”和推荐的方法是使用特定大小的unsigned int
,也许是uint32_t
。
有人能解释为什么会这样吗?这是一个纯粹的教育性问题,我出于好奇而问。
<details>
<summary>英文:</summary>
Here is an example for what I mean:
int open(const char *pathname, int flags);
and from the [man page](https://man7.org/linux/man-pages/man2/open.2.html). Looking into [Linux](https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/uapi/asm/fcntl.h#L18), it is obvious the flags are bit markers.
I am curious by the use of an `int` as a way to set specific bits, as I had thought that the most "portable" and recommended way to do this is to use an `unsigned int` of specific size, perhaps `uint32_t`.
Does anyone have any insight as to why this is? This is a purely educational question and I am asking out of curiosity.
</details>
# 答案1
**得分**: 1
如果我记得没错,从Unix V7开始,`open()` 函数的标志只允许三个值:0(读取),1(写入)和2(读取-写入)。所以,在那个时候,这不是一个“标志”,而是一个接受0、1、2枚举的“模式”:因此是“int”类型。
如果这些确实是标志,逻辑上 `O_RDONLY` 不能是0,`O_RDWR` 应该等于 `O_RDONLY | O_WRONLY`,但事实并非如此。
后来,当添加了其他标志时,保持了“int”类型,以避免在严格控制警告时破坏现有代码的编译。
<details>
<summary>英文:</summary>
If I remember correctly from Unix V7, there were only 3 values allowed for the open() flags: 0 (read) 1 (write) and 2 (read-write). So, at that time, this was not a "flag" but a "mode" taking an enumeration of 0, 1, 2 : hence the "int" type.
If these where really flags, logically O_RDONLY could not be 0 and O_RDWR should be equal to O_RDONLY|O_WRONLY, which is not the case.
Later, when other flags were added, the type was kept "int" to avoid breaking the compilation of existing code when using severe control of the warnings.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论