这篇文章是程序自动发表的, 详情可以见这里
文件描述符
非负整数, 默认使用最小的可用的整数
0,1,2 对应 STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO
读写函数
#include<unistd.h>
- int open(const char path,int oflag … /*mode/);oflag: 5 必须选 1: O_RDONLY, O_WRONLY, O_RDWR, O_SEARCH, O_EXEC
可选: O_APPEND, O_CREAT, O_EXCL, O_SYNC, O_TRUNC
eg O_WDONLY | O_CREAT | O_TRUNC - int close(int fd);
- off_t lseek(int fd, off_t offset, int whence)whence: SEEK_SET, SEEK_CUR, SEEK_END 错误则返回 - 1offset 可负, 可以超过文件大小, 在超过文件大小后写, 会形成空洞, 用 \ 0 填补, 但是不占用磁盘块
- ssize_t read(int fd, void *buf,size_t nbytes);if 未到 EOF, 则读取 nbytes, 返回 nbytes, 否则剩多少, 读多少, 返回多少 (到 EOF 就是 0)
- ssize_t write(int fd, void *buf,size_t nbytes);io 效率: buf 设置为 4096 及更大效率较高
进程文件结构
文件共享
原子操作
一般有多个函数的操作,, 不是原子操作, 多进程运行时可能出错, 比如
seek pointer to end
write
单进程没有问题, 而多进程访问同一个文件, 而不是同一个文件描述符时, 比如 a,b 访问 f
当 a 执行完 seek 到 end 后 , 写指针在 n, b 执行 seek to end 然后写至 x bytes, 此时文件指针已经到 n x, 但是 a 会在 n 处继续执行写, 然后就覆盖了 bxx 的内容
复制文件描述符 dup dup2
#include<unistd.h>
int dup(int fd); // copy fd
int dup2(int fd,int fd2)
// close fd2 and open fd, note it's an atomic op
//if fd2==fd : return fd2
参考资料: UNIX 环境高级编程 W.Richard Stevens, Stephen A. Rago