使用O_RDWR与O_RDONLY | O_WRONLY

sir*_*lot 11 c++ linux

在我的简单程序中:

#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());
}
Run Code Online (Sandbox Code Playgroud)

我使用组合打开终端流O_RDONLY| O_WRONLY,这似乎工作正常.我得到你应该使用O_RDWR它,因为它使语义更清晰,但我的问题是,如果加入两个现有的标志已经有效,为什么还要创建一个完整的另一个标志呢?是否有一些历史原因,或者我只是忽略了什么,这实际上并没有起作用?

Mat*_*son 27

O_RDONLY | O_WRONLY(至少在我的Linux机器上)不是一回事O_RDWR.

#define O_RDONLY         00
#define O_WRONLY         01
#define O_RDWR           02
Run Code Online (Sandbox Code Playgroud)

它工作的事实看起来像一个错误/功能/巧合,而不是"它的工作原因,因为它应该这样工作".

  • FWIW:Posix说:"应用程序应在oflag的值中指定下面前五个值(文件访问模式)中的一个:"其中五个是"O_EXEC","O_RDONLY","O_RDWWR","O_SEARCH"和"O_WRONLY" `. (8认同)
  • 当然,他没有测试阅读,所以他不知道阅读是否真的有效。 (3认同)