Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using O_RDWR vs O_RDONLY | O_WRONLY

Tags:

c++

linux

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 should use O_RDWR because 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?

like image 506
sircodesalot Avatar asked Oct 14 '13 16:10

sircodesalot


1 Answers

O_RDONLY | O_WRONLY (at least on my Linux machine) is not the same thing as 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".

like image 102
Mats Petersson Avatar answered Sep 21 '22 00:09

Mats Petersson