在这篇文章中,我们将整理一份 unistd.h
常用函数速查表 ,便于快速查找和记忆,涵盖文件 I/O、进程管理、系统信息、用户/组信息等方面。
unistd.h
常用函数速查表(POSIX/Linux/macOS)
1. 文件与 I/O 操作函数 说明 示例 int access(const char *path, int mode)
检查文件权限/存在性(R_OK
读,W_OK
写,X_OK
执行,F_OK
存在) access("file.txt", R_OK)
off_t lseek(int fd, off_t offset, int whence)
改变文件指针位置(SEEK_SET
, SEEK_CUR
, SEEK_END
) lseek(fd, 0, SEEK_SET)
ssize_t read(int fd, void *buf, size_t count)
从文件描述符读取数据 read(fd, buf, 100)
ssize_t write(int fd, const void *buf, size_t count)
向文件描述符写入数据 write(fd, buf, len)
int close(int fd)
关闭文件描述符 close(fd)
2. 进程管理函数 说明 示例 pid_t fork(void)
创建子进程 pid_t pid = fork();
pid_t getpid(void)
获取当前进程 PID getpid()
pid_t getppid(void)
获取父进程 PID getppid()
void _exit(int status)
立即退出进程(不执行清理) _exit(0)
int execv(const char *path, char *const argv[])
启动新程序(替换当前进程镜像) execv("/bin/ls", args)
3. 系统 & 休眠函数 说明 示例 unsigned int sleep(unsigned int seconds)
秒级休眠 sleep(2)
int usleep(useconds_t usec)
微秒级休眠 usleep(500000)
long sysconf(int name)
获取系统配置信息(如 _SC_NPROCESSORS_ONLN
CPU 数) sysconf(_SC_PAGESIZE)
long pathconf(const char *path, int name)
获取路径上的系统限制 pathconf("/", _PC_NAME_MAX)
4. 用户 / 组信息函数 说明 示例 uid_t getuid(void)
获取实际用户 ID getuid()
uid_t geteuid(void)
获取有效用户 ID geteuid()
gid_t getgid(void)
获取实际组 ID getgid()
gid_t getegid(void)
获取有效组 ID getegid()
5. 常用宏定义宏 说明 R_OK
可读权限 W_OK
可写权限 X_OK
可执行权限 F_OK
文件是否存在 SEEK_SET
文件开头 SEEK_CUR
当前位置 SEEK_END
文件末尾
6. 示例:检查文件并读取内容
# include <unistd.h>
# include <fcntl.h>
# include <iostream> int main ( ) { if ( access ( "test.txt" , R_OK) != 0 ) { std:: cerr << "File not readable or not exist.\n" ; return 1 ; } int fd = open ( "test.txt" , O_RDONLY) ; if ( fd == - 1 ) { perror ( "open" ) ; return 1 ; } char buf[ 100 ] ; ssize_t n = read ( fd, buf, sizeof ( buf) - 1 ) ; if ( n >= 0 ) { buf[ n] = '\0' ; std:: cout << "Content: " << buf << "\n" ; } close ( fd) ; return 0 ;
}