自从工作了,再也没有更新过这个技术博客。一来工作了没什么好写的,二来确实也挺忙。最近稍微有点空闲,先开一个写一点吧。
使用方法:#define _FILE_OFFSET_BITS 64 #define __USE_XOPEN2K #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <getopt.h> const struct option dcache_options[] = { {"sync",0,NULL,'s'}, {"help",0,NULL,'h'}, {NULL,0,NULL,0} }; void usage(char* proc_name,int exit_code) { printf("dcache is an utility to drop file cache.\n" "usage:%s [-s] file\n" "\t-s,--sync, sync data before drop cache.\n" "\t-h,--help, print help.\n",proc_name); exit(exit_code); } int dcache(int fd, int sync_data) { off_t off,len; struct stat buf; int save_errno; save_errno = errno; if (sync_data) { if (fsync(fd) < 0) { printf("%s\n",strerror(errno)); errno = save_errno; return -1; } } if (fstat(fd,&buf) < 0) { printf("%s\n",strerror(errno)); errno = save_errno; return -1; } off = 0; len = buf.st_size; if (posix_fadvise(fd,off,len,POSIX_FADV_DONTNEED) < 0) { printf("%s\n",strerror(errno)); errno = save_errno; return -1; } return 0; } int main(int argc, char* argv[]) { int c,fd; char* file; int long_index = 0; int print_help = 0; int sync_data = 0; while ((c = getopt_long(argc,argv,"sh",dcache_options,&long_index)) != -1) { switch (c) { case 's': sync_data = 1; break; case 'h': print_help = 1; break; default: printf("unknown option -%c\n",c); usage(argv[0],EXIT_FAILURE); break; } } if (print_help) { usage(argv[0],EXIT_SUCCESS); } if (optind >= argc) { printf("file name required\n"); exit(EXIT_FAILURE); } for (c = optind; c < argc; ++c) { file = argv[c]; if ((fd = open(file,O_RDWR)) < 0) { printf("open %s failed.\n",file); } else { printf("drop cache of %s %s.\n",file,dcache(fd,sync_data) == 0?"success":"failed"); close(fd); } } exit(EXIT_SUCCESS); }