1、I/O操作
#include <iostream> #include <cstdio> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <string> using namespace std; /* function: get the inode of the input file input: file descriptor */ int get_inode(int fd) { struct stat buf; int ret; ret = fstat(fd, &buf); if(ret < 0) { perror("fstat"); return -1; } return buf.st_ino; } int main() { struct stat sb; off_t len; char *p; int fd; printf("the memory page size is: %d/n", getpagesize()); printf("the memory page size is: %d/n", sysconf(_SC_PAGE_SIZE)); string filename; cout<<"please input the file name:"; cin>>filename; fd = open(filename.c_str(), O_RDONLY); printf("the file descriptor is %d/n", get_inode(fd)); if(-1 == fd) { perror("open"); return 1; } if(fstat(fd, &sb) == -1) { perror("fsat"); return 1; } if(!S_ISREG(sb.st_mode)) { fprintf(stderr, "%s is not a file/n", filename.c_str()); } //chuang jian nei cun wen jian ying she p = static_cast<char*>(mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0)); if(p == MAP_FAILED) { perror("mmap"); return 1; } if(close(fd) == -1) { perror("close"); return 1; } for(len = 0; len < sb.st_size; ++len) putchar(p[len]); // close the memory file mapping if(munmap(p, sb.st_size) == -1) { perror("munmap"); return 1; } return 0; }
2、文件和目录管理
#include <iostream> #include <cstdio> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <cstring> #include <dirent.h> using namespace std; /* *find the file in dir, *if the file in the dir, return 0 */ int find_file_in_dir(const char *path, const char *file) { struct dirent *entry; int ret = 1; DIR *dir = opendir(path); while((entry = readdir(dir)) != NULL) { if(strcmp(entry->d_name, file)) { ret = 0; break; } } if(!entry) perror("readdir"); closedir(dir); return ret; } int main() { string path, file; cout<<"please input the path name:"; cin>>path; cout<<"please input the file name:"; cin>>file; if(find_file_in_dir(path.c_str(), file.c_str()) == 0) cout<<"Find!"<<endl; else cout<<"Not find!"<<endl; //create hard link link("/home/flybird/array.sh", "/home/flybird/array.sh.hard"); //create soft link symlink("/home/flybird/array.sh", "/home/flybird/array.sh.soft"); }
3、内存管理
1、创建匿名内存映射
2、映射/dev/zero文件
int main() { void *p; int fd; /*open file /dev/zero to read and write*/ fd = open("/dev/zero", O_RDWR); if(fd == -1) { perror("open"); return -1; } /*make maping to /dev/zero*/ p = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if(p == MAP_FAILED) { perror("mmap"); if(close(fd)) perror("close"); return -1; } /*close the /dev/zero */ if(close(fd)) perror("close"); /*free p*/ int ret = munmap(p, getpagesize()); if(ret) perror("munmap"); }
类UNIX 操作系统中, /dev/zero 是一个特殊的文件,当你读它的时候,它会提供无限的空字符(NULL, ASCII NUL, 0x00)。其中的一个典型用法是用它提供的字符流来覆盖信息,另一个常见用法是产生一个特定大小的空白文件。BSD就是通过mmap把/dev/zero映射到虚地址空间实现共享内存的。可以使用mmap将/dev/zero映射到一个虚拟的内存空间,这个操作的效果等同于使用一段匿名的内存(没有和任何文件相关)。