fcntl()
PROTOTYPE
#include <posix.h>
int fcntl(int fid, int cmd, ...);
DESCRIPTION
fcntl() performs the operation indicated by cmd on the open file specified by fid. The supported operations are F_DUPFD, F_GETFL, and F_SETFL.
For F_DUPFD, fcntl() takes a third parameter arg of type “int”. It allocates the lowest numbered free descriptor greater than or equal to arg and duplicates the file control block referenced by fid. If successful, fcntl() returns the duplicate file descriptor. Otherwise, it sets errno and returns -1. The duplicate descriptor must be freed (by close() or equivalent) when no longer needed.
F_GETFL reads the file’s access mode and status settings. No additional fcntl() parameters are used. Some combination of the following flags will be set in the return value:
File Access Mode Flags:
- O_RDONLY - Open for reading only
- O_WRONLY - Open for writing only
- O_RDWR - Open for both reading and writing
File Status Flags:
- O_APPEND - sets the current position to the end of file before each file write
- O_ASYNC - present for compatibility, no effect on Blunk file system
- O_NONBLOCK - present for compatibility, no effect on Blunk file system
- O_DIRECT - allows data cache bypassing (non-standard)
- O_NO_OVERWRITE - overwrites use new clusters (non-standard, TargetXFS only)
O_RDONLY is defined as ‘0’, so you can’t directly test for it. If neither O_WRONLY nor O_RDWR are set, then effectively O_RDONLY is set.
F_SETFL sets the file’s status flags according to the value of a third fcntl() parameter arg of type “int”. Bits other the status flags defined above are ignored. All status flags are overwritten by each call, so to only change specific flags, do a read-modify-write by calling fcntl() with F_GETFL first and then F_SETFL. For maximum compatibility, bits you don’t care about should be preserved.
If successful, fcntl() returns 0. Otherwise, errno is set and -1 returned.
ERROR CODES
| EBADF | fid is not the descriptor of an open file (F_GETFL or F_SETFL) or not open in read-only mode (F_DUPFD). |
| EINVAL | cmd is invalid or cmd is F_DUPFD and the third parameter is not in [0, FOPEN_MAX-1]. |
| EMFILE | cmd is F_DUPFD and FOPEN_MAX files are currently open. |
EXAMPLE
/*-------------------------------------------------------------------*/
/* Get file ID for stdout and use duplicate to write "Hello\n". */
/*-------------------------------------------------------------------*/
fid = fileno(stdout);
fid2 = fcntl(fid, F_DUPFD, 0);
if (fid2 == -1)
error("fcntl() failed");
write(fid2, "Hello\n", 6);
close(fid2);
...
int flags;
/*-------------------------------------------------------------------*/
/* Add append mode to file descriptor. */
/*-------------------------------------------------------------------*/
flags = fcntl(fid, F_GETFL);
if (flags == -1)
error("fcntl(F_GETFL) failed");
flags |= O_APPEND;
if (fcntl(fid, F_SETFL, flags))
error("fcntl(F_SETFL) failed");