fcntl64 - Linux
Overview
fcntl64 allows manipulation of file descriptor flags, file status flags, and record locks on files open in a file descriptor.
Syntax
#include <fcntl.h>
int fcntl64(int fd, int cmd, ... /* arg */);
Where:
- fd: File descriptor referencing the file to be manipulated
- cmd: Command to execute on the file descriptor
- arg: Optional argument for certain commands
Options/Flags
| Option | Description |
|—|—|
| F_DUPFD | Duplicate file descriptor |
| F_GETFD | Get file descriptor flags |
| F_SETFD | Set file descriptor flags |
| F_GETFL | Get file status flags |
| F_SETFL | Set file status flags |
| F_GETLK | Get record lock |
| F_SETLK | Set record lock |
| F_SETLKW | Set record lock and wait if locked |
| O_APPEND | Open file for appending data |
| O_CREAT | Create file if it doesn’t exist |
| O_EXCL | Ensure file doesn’t exist before creating |
| O_NOCTTY | Don’t make terminal the controlling terminal |
| O_NONBLOCK | Open file in non-blocking mode |
| O_RDONLY | Open file for reading only |
| O_RDWR | Open file for both reading and writing |
| O_SYNC | Open file for synchronous I/O |
| O_TRUNC | Truncate file to 0 length |
| O_WRONLY | Open file for writing only |
Examples
Duplicate File Descriptor
int new_fd = fcntl64(fd, F_DUPFD);
Set File Status Flags
int flags = fcntl64(fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl64(fd, F_SETFL, flags);
Get Record Lock
struct flock lock;
fcntl64(fd, F_GETLK, &lock);
if (lock.l_type == F_UNLCK) {
// File is unlocked
}
Set Record Lock
struct flock lock = {
.l_type = F_WRLCK,
.l_whence = SEEK_SET,
.l_start = 10,
.l_len = 100
};
fcntl64(fd, F_SETLK, &lock);
Common Issues
Permission Denied: Ensure you have sufficient permissions to perform the desired operation on the file.
Invalid File Descriptor: Verify that the file descriptor is valid and refers to an open file.
Lock Conflicting: When setting a lock, ensure it doesn’t conflict with existing locks held by other processes.
Integration
Combine with dup2()
int fd = open("file.txt", O_RDWR);
dup2(fd, 1); // Redirect stdout to file.txt
Create Custom Commands
#include <sys/ioctl.h>
int my_fcntl(int fd, int cmd) {
return fcntl64(fd, cmd, 0);
}