系统函数调用中的整数标志

huangapple go评论67阅读模式
英文:

integer flags in system function calls

问题

以下是您要翻译的内容:

这是一个我所指的示例:

```c
int open(const char *pathname, int flags);

并来自man页面。查看Linux,很明显这些标志是位标记。

我对将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 &quot;portable&quot; 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 &quot;flag&quot; but a &quot;mode&quot; taking an enumeration of 0, 1, 2 : hence the &quot;int&quot; 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 &quot;int&quot; to avoid breaking the compilation of existing code when using severe control of the warnings.

</details>



huangapple
  • 本文由 发表于 2023年6月16日 03:20:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定