Linux 使用 O_RDWR 与 O_RDONLY | O_WRONLY

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19365109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:05:26  来源:igfitidea点击:

Using O_RDWR vs O_RDONLY | O_WRONLY

c++linux

提问by sircodesalot

In my simple program:

在我的简单程序中:

#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sstream>

using namespace std;

int main(int argc, char *argv[]) {
    stringstream ss;
    ss << "What does the quick brown fox say?" << endl;

    int file_descriptor = open("/dev/tty", O_RDONLY | O_WRONLY);
    write(file_descriptor, ss.str().c_str(), ss.str().size());
}

I open the terminal stream using the combination O_RDONLY| O_WRONLY, and this seems to work fine. I get that you shoulduse O_RDWRbecause it makes clearer semantic sense, but my question is why bother creating a whole other flag if joining two existing flags already works? Is there some historical reason for this, or am I just overlooking something, and this really doesn't actually work?

我使用组合打开终端流O_RDONLY| O_WRONLY,这似乎工作正常。我知道您应该使用O_RDWR它,因为它具有更清晰的语义,但我的问题是,如果连接两个现有标志已经有效,为什么还要创建一个完整的其他标志?这有什么历史原因,还是我只是忽略了一些东西,而这实际上不起作用?

采纳答案by Mats Petersson

O_RDONLY | O_WRONLY(at least on my Linux machine) is not the same thing as O_RDWR.

O_RDONLY | O_WRONLY(至少在我的 Linux 机器上)与O_RDWR.

#define O_RDONLY         00
#define O_WRONLY         01
#define O_RDWR           02

The fact that it works seems like a bug/feature/coincidence rather than "it works because it should work that way".

它工作的事实似乎是一个错误/功能/巧合,而不是“它工作是因为它应该以这种方式工作”。