Flags mask read and write posix - c

Checking the access mode of the file is slightly more complex, since the O_RDONLY (0), O_WRONLY (1), and O_RDWR (2) constants don’t correspond to single bits in the open file status flags. Therefore, to make this check, we mask the flags value with the constant O_ACCMODE, and then test for equality with one of the constants:
accessMode = flags & O_ACCMODE;
if (accessMode == O_WRONLY || accessMode == O_RDWR)
printf("file is writable\n");
I want to understand how the expressiin flags & O_ACCMODE work
Sorry for bad formatting i'm writing from my phone

The file modes are mutually exclusive. You can't be read-only and write-only, and you can't be read-write and either of the other two.
O_ACCMODE is equal to 3 so bits 1 and 2 are on.
00000000 (O_RDONLY)
& 00000011 (O_ACCMODE)
--------
00000000 <-- the result being compared
where 00000000 equals read-only so (accessMode == O_RDONLY) returns true.
The same for the others.
00000001 (O_WRONLY)
& 00000011 (O_ACCMODE)
---------
00000001 <-- the result being compared
O_WRONLY is 1 so (accessMode == O_WRONLY) is "is 1 equal to 1" which naturally returns true.

I don't think the above answer given by #Duck here is correct. Given the examples it makes no sense to mask them.
The reason you need to mask is that
flags = fcntl(fd, F_GETFL);
returns more than just these two bits. In fact the return value could be something like this:
1000000000000001
for write only file.
We mask in order to get rid of those other bits, which are not related to the read/write permissions.

In this O_ACCMODE is used as and mask to get access mode bits.

Related

POSIX flags - how to set all of them / individual ones

I have this peice of code that should read from a pseudo terminal and print to another pseudo terminal (stdin):
// Declare & define a file descriptor.
int fd;
int status;
char string[] = "XXXX";
char buffer[8];
// Establish connection between a file and the file descriptor.
fd = open("/dev/pts/4", O_RDWR);
// Check if connection was established.
if(fd == -1){
printf("Assigning failed: %s\n", strerror(errno));
}
else{
fputs("Assigning successful!\n", stdout);
// Set some flags for the connection.
fcntl(fd, F_SETFL, 0);
}
// Read from the connection.
status = read(fd, buffer, 8);
if (status == -1){
printf("Read failed: %s\n", strerror(errno));
}
else{
printf("I read this: %s\n", buffer);
}
return 0;
I don't know exactly what fcntl(fd, F_SETFL, 0); does, but untill I used it I wasn't able to read from the /dev/pts/4. After I used it for the first time I could read normaly, even if I commented out this line of code.
I tried to explain it to myself reading POSIX...
F_SETFL flag is defined in the POSIX as:
Set the file status flags, defined in <fcntl.h>, for the file
description associated with fildes from the corresponding bits in the
third argument, arg, taken as type int. Bits corresponding to the file
access mode and the file creation flags, as defined in <fcntl.h>, that
are set in arg shall be ignored. If any bits in arg other than those
mentioned here are changed by the application, the result is
unspecified. If fildes does not support non-blocking operations, it is
unspecified whether the O_NONBLOCK flag will be ignored.
So it sets file status flags asociated with the 1st argument (file descriptor) of fnctl() to 0? I found an explanation about the status flags in the POSIX:
The <fcntl.h> header shall define the following symbolic constants for
use as file status flags for open(), openat(), and fcntl(). The values
shall be suitable for use in #if preprocessing directives.
O_APPEND Set append mode. O_DSYNC Write according
to synchronized I/O data integrity completion. O_NONBLOCK
Non-blocking mode. O_RSYNC Synchronized read I/O
operations. O_SYNC Write according to synchronized I/O
file integrity completion.
So does fcntl(fd, F_SETFL, 0); set all those to 0? Are all of those flags a single bit? How do I only set one of them to 1 or 0? And how do I know which bit is assigned to which flag?
It's a bitmask. Each flag is a bit (or several bits) in the integer you pass to fcntl. Each symbolic constant expands to a number in which only the corresponding bit(s) is set, and so you can set several flags by ORing them together. For instance, if bit 2 is the append flag, then O_APPEND would be 0b100 == 4; if bit 3 is the nonblock flag, then O_NONBLOCK would be 0b1000 == 8, and so on. But by using the symbolic constants, you don't need to know which bits they actually are, which is good since they may vary between OSes.
In fcntl(fd, F_SETFL, 0), the number 0 has no bits set, so all the flags are cleared. To set append and clear the rest, you could do fcntl(fd, F_SETFL, O_APPEND);. To set both append and nonblock, OR their constants together: fcntl(fd, F_SETFL, O_APPEND | O_NONBLOCK);
With similar bit operations, you can operate on the flags returned by fl = fcntl(fd, F_GETFL):
int fl = fcntl(fd, F_GETFL);
if (fl & O_APPEND) { ... } // test if in append mode
fcntl(fd, F_SETFL, fl | O_NONBLOCK); // turn on nonblock and keep everything else the same
fcntl(fd, F_SETFL, fl & ~O_DSYNC); // turn off dsync and keep everything else the same
There's some more examples here.

What does 0 flag mean in shmflg for shared V memory system calls?

int shmget(key_t key, size_t size, int shmflg);
The above function is given as per man shmget. The flags available for the third parameters are given in the man and are well defined. But time to time I see people using 0 passed to the flag. What does the 0 mean? I can't find anywhere online the meaning of 0.
The format of shmflg is as follows:
11 10 9 8 0 : bits
---------------------------------------------------------
| additional flags | IPC_EXCL | IPC_CREAT | mode flags |
---------------------------------------------------------
The mode flags are interpreted in the same ways as the flags parameter of the open system call. A value of zero for the mode flags means O_RDONLY.
The values of bits 9 and 10 are to be interpreted as follows:
00 : Use the existing segment associated with the key. If it does not exist, return the error ENOENT.
01 : Create a new segment if the segment associated with the key does not exist. Otherwise, use the existing segment.
10 : I think this is treated the same as 00 (can someone confirm?).
11 : Create a new segment if the segment associated with the key does not exist. Otherwise, return the error EEXIST.
Of course, an existing segment can only be accessed if the current user has the required permissions.
A value of zero for the additional flags means a normal segment (no SHM_HUGETLB or other such flags).

How does the combination of flags in system call open() work?

fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);
My tuition tells me that this O_WRONLY | O_CREAT | O_TRUNC means the system call allows to write and create (if any) and truncate file (if any).
But isn't it | is one of the bitwise operator and means OR?
How does the system interpret the combination? I tried to use what I learn about bitwise operation to interpret this combination, but I just get lost. Can someone explain this?
Bitwise OR and flags are a bit unintuitive.
Say you have the following flags:
int FLAG_1 = 0x1; // in binary, 0001
int FLAG_2 = 0x2; // in binary, 0010
int FLAG_3 = 0x4; // in binary, 0100
When you use:
int flags = FLAG_1 | FLAG_3;
the value of flags in binary is 0101. That means, the following flags have been set: FLAG_1 AND FLAG_3.
Given the value of flags, you can check whether FLAG_3 has been set by using bitwise AND.
if ( flags & FLAG_3 != 0 )
{
// FLAG_3 has been set.
}
Same logic is used when you combine the flags as O_WRONLY | O_CREAT | O_TRUNC.
More information on bitmasking can be found at http://en.wikipedia.org/wiki/Mask_(computing).

Meaning of FLAG in socket send and recv

While searching in the Linux manual page, what I have found about the format of send and recv in socket is like below:
For send,
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
For recv,
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
But I am not sure what they are trying to tell about int flags. In one sample code I have found the value of flag as 0 (zero). What it means? Also what is the meaning of the line below in the man page?
"The flags argument is the bitwise OR of zero or more of the following flags."
Then the list of flags:
MSG_CONFIRM
MSG_DONTROUTE
.
.
.
etc.
if int flags are equal to 0, it means that no flags are specified. these are optional.
to answer about ORing flags - it is a mechanism that allow you to specify more than one flag - MSG_CONFIRM | MSG_DONTWAIT specify two flags.
OR gate: AND gate:
a b out a b out
0 0 0 0 0 0
0 1 1 0 1 0
1 0 1 1 0 0
1 1 1 1 1 1
what i understand, is that by ORing flags you set specific bits to 1 in an int variable.
later in the code, by ANDing that variable with specific flags you know whether flag was set or not.
if you had specified MSG_DONTWAIT flag, the code: flags & MSG_DONTWAIT will return 1, so you know that flag was set.
let's have a look how MSG_DONTWAIT is defined.
enum
{
...
MSG_DONTWAIT = 0x40, /* Nonblocking IO. */
#define MSG_DONTWAIT MSG_DONTWAIT
...
};
the hex notation 0x40 means that only 7th bit is set to 1.
below i present an example of bitwise operations from socket.c. there's a check whether O_NONBLOCK flag was set when socket file descriptor was created. if so, then set on current flags variable 7th bit to 1, which was defined as MSG_DONTWAIT.
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
a nice reference about bitwise operations: http://teaching.idallen.com/cst8214/08w/notes/bit_operations.txt
Flags allow to pass extra behavior. The default value (0) will lead to the default behavior. In most of the simple cases that's what you want.
If you want the network subsystem to behave in a specific way you can pass on flag value or several values by Oring them: For example If you want to have the 'MSG_DONTWAIT' and the 'MSG_MORE' behaviour (as described by the man page) you can use MSG_DONTWAIT | MSG_MORE.
Here's a good explanation, with an example.
The 0 flag allows you to use a regular recv(), with a standard behavior.
If you want to use a custom recv(), you need to separate your flags (thoses who're listed in the man page) with the OR operator, as it's stated here :
"The flags argument is the bitwise OR of zero or more of the following flags."
Just like that :
recv(sockfd, buf, buflen, FLAG | FLAG | FLAG);

How to calculate the bit flags/enum flags for oflag in open()?

I'm working on a networking assignment and we are tasked with creating a remote file access server with a protocol we were given. My difficulties come in the lack of information I can find that explains the process of calculating the bits for the oflag argument in open().
I receive a message from a client to open a file and in the message I parse characters for the flags to use in oflag. Specifically they are:
R - O_RDONLY
W - O_WRONLY
RW - O_RDWR
A - O_APPEND
C - O_CREAT
T - O_TRUNC
E - O_EXCL
I went around Google and searched bitwise operations, enumeration flags, bit flags, calculating bit flags, etc. and couldn't find something that was useful in figuring out how to create the bits for oflag. Maybe I just didn't know what I was looking for and overlooked useful information?
Could someone please:
Point me in the direction/provide links to documentation/example of how to calculate the bits/# I ought to put into oflags given my parsed characters or
Show me the enumeration types for the flags and the ordering they ought to go in
Thanks a bunch for you help and if I wasn't clear on my problem or what I am trying to do, just let me know and I will clarify ASAP.
The O_... flags are numbers each with a different single bit set. For example on my system they are defined in fcntl.h as
#define O_RDONLY 00
#define O_WRONLY 01
#define O_RDWR 02
#define O_CREAT 0100 /* not fcntl */
#define O_EXCL 0200 /* not fcntl */
#define O_NOCTTY 0400 /* not fcntl */
#define O_TRUNC 01000 /* not fcntl */
#define O_APPEND 02000
You use | (logical OR) to combine the flags and pass in a single number to open with all the bits set for each option you want. So e.g. open("file", O_RDWR | O_CREAT).
You can compute an int and pass that into open too if you want.
int flags = 0;
if (...)
flags |= O_RDWR;
...
open('file', flags);
The usual expression would be something like O_RDWR | O_CREAT. And note that O_RDWR is exactly O_RDONLY | O_WRONLY
You can do something like this:
char *flags = "r";
int oflag = 0;
if (strchr(flags,'r')) oflag |= O_RDONLY;
and so on for the rest of the flags.

Resources