打开和关闭文件
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <stdio.h>
#include <cstdlib>
int main(int argc, char **argv) {
int file_fd=open("/home/yang/acm/untitled/in.txt",O_RDWR,0);
/* flags: S_IRUSR
* O_RDONLY
* O_WRONLY
* O_RDWR
* O_CREAT
* O_TRUNC
* O_APPEND
*/
if(file_fd<0){
printf("open file error\n");
exit(1);
}
char str[100]="test1";
int err=write(file_fd,str,strlen(str));
if(err<0)
{
printf("error\n");
exit(1);
}
close(file_fd);
return 0;
}
dup2(int old_fd,int new_fd);
拷贝描述符
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <stdio.h>
#include <cstdlib>
#include <sys/wait.h>
int main(int argc, char **argv) {
int file_fd = open("/home/yang/acm/untitled/in.txt", O_RDWR, 0);
int file_fd2 = open("/home/yang/acm/untitled/in.txt", O_RDWR, 0);
char c;
dup2(file_fd,file_fd2);
read(file_fd,&c,1);
read(file_fd2,&c,1);
printf("%c",c);
return 0;
}
file_fd1和file_fd2本来不同描述符,通过dup2() 拷贝描述符号,所以共享同一个 v-node表