文件共享
一个进程打开了两个文件
文件表条目(file-table-entry):
1.文件状态标志(file-status-flags): 读/写/追加/同步/非阻塞等;
2.当前文件偏移量
3.v节点指针
- //验证
- int main(int argc, char *argv[])
- {
- int fd1 = open("test.txt", O_RDONLY);
- if (fd1 == -1)
- err_exit("fd1 open O_RDONLY error");
- int fd2 = open("test.txt", O_RDWR);
- if (fd2 == -1)
- err_exit("fd2 open O_RDWR error");
- //读取fd1
- char buf[BUFSIZ];
- if (read(fd1, buf, 10) == -1)
- err_exit("read fd1 error");
- cout << "fd1: " << buf << endl;
- //读取fd2
- bzero(buf, 10);
- if (read(fd2, buf, 10) == -1)
- err_exit("read fd1 error");
- cout << "fd2: " << buf << endl;
- lseek(fd1, 0, SEEK_SET);
- lseek(fd2, 0, SEEK_SET);
- write(fd2, "Helloworld", 10);
- bzero(buf, 10);
- if (read(fd1, buf, 10) == -1)
- err_exit("read fd1 error");
- cout << "after fd2 write: " << buf << endl;
- }
两个独立的进程打开同一个文件
复制文件描述符
方法有三种:
1.dup
2.dup2
其中dup2相当于先close在执行dup。
- #include <unistd.h>
- int dup(int oldfd);
- int dup2(int oldfd, int newfd);
- //示例
- int main(int argc, char *argv[])
- {
- int fd = open(</