Setting FD flags in Linux

1

I was under the impression that fcntl(fd, F_SETFD, flg ) and flg = fcntl(fd, F_GETFD, flg ) could be used for setting and getting filedescriptor flags.

According to https://community.spiceworks.com/linux/man/2/fcntl, linux should only support the setting of some fd flags. Fair enough. But judging by the output of:

#define _GNU_SOURCE
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>

#define XSZ(x) (int)(sizeof(x)*2)
int main(int argc, char** argv){
    int fd, flg;
    if ( (fd = open("/dev/stdout", O_RDWR )) < 0){ perror("open"); return -errno; }

    //get
    if ( (flg = fcntl(fd, F_GETFD)) < 0 ){ perror("setfd"); return -errno; }
    printf("flg=0x%0*x\n", XSZ(flg), flg);

#define ADD_FLAG(FLG) \
    flg |= FLG;\
    printf("setting flg=0x%0*x\n", XSZ(flg), flg);\
    if ( (flg = fcntl(fd, F_SETFD, flg )) ){ perror("setfd"); return -errno; }\
    if ( (flg = fcntl(fd, F_GETFD, flg )) < 0 ){ perror("getfd"); return -errno; }\
    printf("flg=0x%0*x\n\n", XSZ(flg), flg);

    ADD_FLAG(FD_CLOEXEC);
    ADD_FLAG(O_APPEND);
    ADD_FLAG(O_DIRECT);
    ADD_FLAG(O_ASYNC);
    ADD_FLAG(O_NOATIME);

    return 0;
}

being

flg=0x00000000
setting flg=0x00000001
flg=0x00000001

setting flg=0x00000401
flg=0x00000001

setting flg=0x00004001
flg=0x00000001

setting flg=0x00002001
flg=0x00000001

setting flg=0x00040001
flg=0x00000001

It looks like the only settable flag is FD_CLOEXEC. (Weird thing: all the set calls return succesfully).

And it looks to me like the kernel pretty much ignore the arguments to F_SETFD:

https://github.com/torvalds/linux/blob/master/fs/fcntl.c#L259

What's going on here? Am I missing something?

c
linux
unix
posix
asked on Stack Overflow Jun 18, 2016 by PSkocik

1 Answer

3

The only valid flag for F_SETFD is FD_CLOEXEC; all the others you use are for F_SETFL. Neither Linux nor POSIX specify any error when F_SETFD is passed any values for flags that don't exist, so it is expected that such a situation will not result in an error.


User contributions licensed under CC BY-SA 3.0