Specification of file descriptors

后端 未结 2 567
别那么骄傲
别那么骄傲 2021-01-26 14:23

I am trying to understand flags and modes of file descriptors.

The man page for

fcntl - manipulate file descriptor

int fcntl(int fd, int cmd);
<         


        
2条回答
  •  既然无缘
    2021-01-26 15:09

    File descriptors can be duplicated. For example, when a process forks, it gets its own set of FDs that the parent doesn't affect, and the dup syscall can be used to explicitly duplicate individual FDs.

    When file descriptors get duplicated, every descriptor has its own set of file descriptor flags, but they'll all share the same file status flags. For example, consider this code:

    int fdA = open('/tmp/somefile', O_WRONLY);
    int fdB = dup(fdA);
    fcntl(fdA, F_SETFD, FD_CLOEXEC);
    fcntl(fdA, F_SETFL, O_APPEND);
    

    After running it, fdA will be close-on-exec and in append mode, and fdB will be in append mode but not close-on-exec. This is because close-on-exec is a file descriptor flag and append mode is a file status flag.

    The file access mode and file creation flags are passed along with the file status flags when they're supported.

    The third parameter to open, also confusingly called mode, is unrelated to everything else discussed so far. If the file is created by the call to open, then that mode is used as the permissions for the new file. Otherwise, it has no effect.

    • FD_CLOEXEC - file descriptor flag
    • O_RDONLY - file access mode
    • O_WRONLY - file access mode
    • O_RDWR - file access mode
    • O_CLOEXEC - file creation flag
    • O_CREAT - file creation flag
    • O_DIRECTORY - file creation flag
    • O_EXCL - file creation flag
    • O_NOCTTY - file creation flag
    • O_NOFOLLOW - file creation flag
    • O_TMPFILE - file creation flag
    • O_TRUNC - file creation flag

    The rest of the flags you listed are file status flags.

    And one final note: O_CLOEXEC is only relevant for a new FD. For existing FDs, you'll only ever use FD_CLOEXEC.

提交回复
热议问题