• Linux系统编程(2)


    手动文件锁定

    1. #include
    2. void flockfile(FILE* stream);
    3. void funlockfile(FILE* stream);
    4. //非阻塞函数
    5. int ftrylockfile(FILE* stream);

    不会锁定流的操作

    1. #define _GNU_SOURCE
    2. #include
    3. int fgetc_unlocked(FILE* stream);
    4. char *fgets_unlocked(char*str, int size, FILE* stream);
    5. size_t fread_unlocked(void* buf, size_t size, size_t nr, FILE* stream);
    6. int fputc_unlocked(int c, FILE* stream);
    7. int fputs_unlocked(const char* str, FILE* stream);
    8. size_t fwrite_unlocked(void * buf, size_t size, size_t nr, FILE* stream);
    9. int fflush_unlocked(FILE* stream);
    10. int feof_unlocked(FILE* stream);
    11. int ferror_unlocked(FILE* stream);
    12. int fileno_unlocked(FILE* stream);
    13. void clearerr_unlocked(FILE* stream);

    标准IO最大的问题在于性能受到两次复制的影响,读取数据时,标准IO会对内核进行read()系统调用,从内核复制数据到标准IO缓冲区,如果有一个应用程序接着通过标准IO送出一个读取请求,则数据会被再复制一次,会从标准IO缓冲区复制到所提供的缓冲区中,写入请求则逆向运作,数据从提供的缓冲区被复制到标准IO缓冲区,然后通过write()系统调用从标准IO缓冲区被复制到内核。

    readv()和writev()

    1. #include
    2. ssize_t readv(int fd, const struct iovec *iov, int count);
    3. ssize_t writev(int fd, const struct iovec* iov, int count);
    4. struct iovec {
    5. void* iov_base;
    6. size_t iov_len;
    7. };

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. int main() {
    9. struct iovec iov[3];
    10. ssize_t nr;
    11. int fd, i;
    12. char* buf[] = {"The term buccaneer comes from the word boucan.\n",
    13. "A boucan is a wooden frame used for cooking mear.\n",
    14. "Buccaneer is the West Indies name for a pirate.\n"};
    15. fd = open("buccaneer.txt", O_WRONLY | O_CREAT | O_TRUNC);
    16. if (fd == -1) {
    17. perror("open");
    18. return 1;
    19. }
    20. // 填三个iovec结果
    21. for (int i = 0; i < 3; i++) {
    22. iov[i].iov_base = buf[i];
    23. iov[i].iov_len = strlen(buf[i]);
    24. }
    25. // 单词调用将他们写出
    26. nr = writev(fd, iov, 3);
    27. if (nr == -1) {
    28. perror("writev");
    29. return 1;
    30. }
    31. printf("wrote %ld bytes\n", nr);
    32. if (close(fd)) {
    33. perror("close");
    34. return 1;
    35. }
    36. return 0;
    37. }
    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. int main() {
    9. // 下面的长度如果变化,结果会有不同的
    10. // char foo[47], bar[50], baz[48];
    11. // char foo[47], bar[51], baz[48];
    12. char foo[47], bar[50], baz[47];
    13. struct iovec iov[3];
    14. ssize_t nr;
    15. int fd, i;
    16. fd = open("buccaneer.txt", O_RDONLY);
    17. if (fd == -1) {
    18. perror("open");
    19. return 1;
    20. }
    21. iov[0].iov_base = foo;
    22. iov[0].iov_len = sizeof(foo);
    23. iov[1].iov_base = bar;
    24. iov[1].iov_len = sizeof(bar);
    25. iov[2].iov_base = baz;
    26. iov[2].iov_len = sizeof(baz);
    27. // 单次调用读取
    28. nr = readv(fd, iov, 3);
    29. if (nr == -1) {
    30. perror("readv");
    31. return 1;
    32. }
    33. for (i = 0; i < 3; i++) {
    34. printf("%d-%ld: %s", i, strlen((char*)iov[i].iov_base), (char*)iov[i].iov_base);
    35. }
    36. if (close(fd)) {
    37. perror("close");
    38. return 1;
    39. }
    40. return 0;
    41. }

    获取页大小

    1. long page_size = sysconf(_SC_PAGESIZE);
    2. 或者
    3. #include
    4. int getpagesize(void);

    页面大小也被静态存储在PAGE_SIZE(定义于)中,因此获取页面大小的第三种方式为int page_size = PAGE_SIZE;

     mmap函数的用法详解及实例分析-CSDN博客

     Linux C | mmap使用实例_mmap使用示例-CSDN博客

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. int main() {
    8. int fd;
    9. void *mmap_addr;
    10. struct stat sb;
    11. fd = open("buccaneer.txt", O_RDONLY);
    12. fstat(fd, &sb);
    13. mmap_addr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    14. if (mmap_addr == MAP_FAILED) {
    15. return -1;
    16. }
    17. printf("%s\n", (char*)mmap_addr);
    18. munmap(mmap_addr, sb.st_size);
    19. close(fd);
    20. return 0;
    21. }

    mmap优点

    相比较于标准的read()和write()系统调用,经过mmap映射有以下优点:

    1、对内存映射文件进行读取和写入操作,可避免使用read和write系统调用时所产生的无关副本,read和write会将数据复制到一个用户空间缓冲区,并从用户缓冲区复制回来。

    2、除了可能的页面失误,对内存映射文件的读写操作不会产生任何系统调用或操作环境切换的开销,进行简单的内存操作即可。

    3、当有多个进程将同一个对象映射至内存时,数据由这些进程共享,对类型为read-only以及shared的可写入映射而言,所共享的是他们的全部,对类型为private的可写入映射而言,所共享的是他们尚未被“写入时复制”的页面。

    4、映射的查找仅涉及很少的指针操作,不需要使用lseek系统调用。

    mmap缺点

    1、内存映射往往是页面大小的整数倍,可能会造成内存浪费。

    2、内存映射必须适合放入进程的地址空间。

    3、创建和维护内存映射以及内核内部相关的数据结构是有代价的。

    调整映射的大小

    1. #define _GNU_SOURCE
    2. #include
    3. #include
    4. void* mremap(void* addr, size_t old_size, size_t new_size, unsigned long flags);

     Linux所特有的mremap系统调用可以用于扩大或者缩小所指定的映射的大小。将位于[addr, addr+old_size)中的内存区间扩大或者缩小为new_size,可能会发生地址移动。

    输出特定文件的iNode编号

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. int get_inode(int fd) {
    7. struct stat buf;
    8. int ret;
    9. ret = fstat(fd, &buf);
    10. if (ret < 0){
    11. perror("fstat");
    12. return -1;
    13. }
    14. return buf.st_ino;
    15. }
    16. int main(int argc, char* argv[]) {
    17. int fd, inode;
    18. if (argc < 2) {
    19. fprintf(stderr, "usage: %s \n", argv[0]);
    20. return 1;
    21. }
    22. fd = open(argv[1], O_RDONLY);
    23. if (fd < 0) {
    24. perror("open");
    25. return 1;
    26. }
    27. inode = get_inode(fd);
    28. printf("%d\n", inode);
    29. return 0;
    30. }

    获取文件的逻辑块

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. /*
    9. *fd相关的文件,映射至logical_block物理块
    10. */
    11. int get_block(int fd, int logical_block) {
    12. int ret;
    13. ret = ioctl(fd, FIBMAP, &logical_block);
    14. if (ret < 0) {
    15. perror("ioctl");
    16. return -1;
    17. }
    18. return logical_block;
    19. }
    20. /*
    21. * get_nr_blocks 返回与fd相关联的文件所耗用的逻辑块的数目
    22. */
    23. int get_nr_blocks(int fd) {
    24. struct stat buf;
    25. int ret;
    26. ret = fstat(fd, &buf);
    27. if (ret < 0) {
    28. perror("fstat");
    29. return -1;
    30. }
    31. return buf.st_blocks;
    32. }
    33. /**
    34. * @brief 输出(logical blocks, physical block)
    35. *
    36. */
    37. void print_blocks(int fd) {
    38. int nr_blocks, i;
    39. nr_blocks = get_nr_blocks(fd);
    40. if (nr_blocks < 0) {
    41. fprintf(stderr, "get_nr_blocks failed!\n");
    42. return;
    43. }
    44. if (nr_blocks == 0) {
    45. printf("no allocated blocks\n");
    46. return;
    47. } else if (nr_blocks == 1) {
    48. printf("1 bllock\n\n");
    49. } else {
    50. printf("%d blocks\n\n", nr_blocks);
    51. }
    52. for (i = 0; i < nr_blocks; i++) {
    53. int phys_block;
    54. phys_block = get_block(fd, i);
    55. if (phys_block < 0) {
    56. fprintf(stderr, "get_block failed!\n");
    57. return;
    58. }
    59. if (!phys_block) {
    60. continue;
    61. }
    62. printf("(%u, %u) ", i, phys_block);
    63. }
    64. putchar('\n');
    65. }
    66. int main(int argc, char* argv[]) {
    67. int fd;
    68. if(argc < 2) {
    69. fprintf(stderr, "usage: %s\n", argv[0]);
    70. return 1;
    71. }
    72. fd = open(argv[1], O_RDONLY);
    73. if (fd < 0) {
    74. perror("open");
    75. return 1;
    76. }
    77. print_blocks(fd);
    78. return 0;
    79. }

    获取进程号和父进程号

    1. #include
    2. #include
    3. pid_t getpid(void);
    4. pid_t getppid(void);

    exec系列调用

    1. #include
    2. int execl(const char* path, const char* arg, ...);
    3. //不定参数必须以NULL结尾
    4. //下面执行会将/bin/vi取代当前所执行的程序
    5. int ret;
    6. ret = execl("/bin/vi", "vi", NULL);
    7. if (ret == -1)
    8. perror("execl");
    1. #include
    2. int execlp(const char* file, const char* arg, ...);
    3. int execle(const char* path, const char* arg, ..., char* const envp[]);
    4. int execv(const char* path, char* const argv[]);
    5. int execvp(const char* file, char* const argv[]);
    6. int execve(const char* filename, char* const argv[], char* const envp[]);

    使用wait检测子进程的状态

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. int main() {
    7. int status;
    8. pid_t pid;
    9. if (!fork()) {
    10. // 子进程
    11. // return 1;
    12. abort();
    13. }
    14. pid = wait(&status);
    15. if (pid == -1)
    16. perror("wait");
    17. printf("pid=%d\n", pid);
    18. if (WIFEXITED(status)) {
    19. printf("Normal termination with exit status=%d\n", WEXITSTATUS(status));
    20. }
    21. if (WIFSIGNALED(status)) {
    22. printf("Killed by signlal=%d%s\n", WTERMSIG(status), WCOREDUMP(status) ? " (dumped core)" : "");
    23. }
    24. if (WIFSTOPPED(status)) {
    25. printf("Stopped by signal=%d\n", WSTOPSIG(status));
    26. }
    27. if (WIFCONTINUED(status)) {
    28. printf("Continued\n");
    29. }
    30. return 0;
    31. }

    等待特定进程waitpid

    1. #include
    2. #include
    3. #include
    4. #include
    5. // pid_t waitpid(pid_t pid, int * status, int options)
    6. /**
    7. * @brief pid参数说明
    8. * <-1 等待其进程组ID等于此值的绝对值的任何子进程,例如传入-500, 则等待进程组ID为500的任何进程
    9. * -1 等待任何子进程,此刻的行为如同wait()
    10. * 0 等待与calling process (进行调用的进程)均属于同一个进程组的任何子进程
    11. * >0 等待其pid等于所指定值的任何子进程,例如传入500,则表示等待进程号为500的子进程
    12. * status参数的行为如同wait的参数,可以使用前面的宏来操作它
    13. * options参数可以是零个或者多个以下选项的OR逻辑运算
    14. * WNOHANG 非阻塞,如果没有符合的子进程终止,则立即放回
    15. * WUNTRACED
    16. * 如果设定了,则设定WIFSTOPPED,及时calling process 并未追踪子进程
    17. * WCONTINUED
    18. * 如果设定了,则设定WIFCONTINUED,即使calling process并为追踪子进程,如同WUNTRACED
    19. */
    20. int main() {
    21. pid_t pid;
    22. int status;
    23. pid = waitpid(2448, &status, WNOHANG);
    24. if (pid == -1) {
    25. perror("waitpid");
    26. } else {
    27. printf("pid=%d\n", pid);
    28. if (WIFEXITED(status)) {
    29. printf("Normal termination with exit status=%d\n", WEXITSTATUS(status));
    30. }
    31. if (WIFSIGNALED(status)) {
    32. printf("killed by signal=%d%s\n", WTERMSIG(status), WCOREDUMP(status) ? " (dump core)" : "");
    33. }
    34. }
    35. return 0;
    36. }

    利用fork(),exec,和waitpid来实现

    1. #include
    2. #include
    3. #include
    4. #include
    5. int my_system(const char* cmd) {
    6. int status;
    7. pid_t pid;
    8. pid = fork();
    9. if (pid == -1) {
    10. perrorr("fork");
    11. return -1;
    12. }
    13. if (pid == 0) {
    14. const char* argv[4];
    15. argv[0] = "sh";
    16. argv[1] = "-c";
    17. argv[2] = cmd;
    18. argv[3] = NULL;
    19. execv("/bin/sh", argv);
    20. exit(-1);
    21. }
    22. if (waitpid(pid, &status, 0) == -1) {
    23. return -1;
    24. } else if (WIFEXITED(status)) {
    25. return WEXITSTATUS(status);
    26. }
    27. retrun 1;
    28. }

    获取和修改资源限制,setrlimit,getrlimit

    1. #include
    2. #include
    3. #include
    4. #include
    5. /**
    6. * @brief
    7. * struct rlimit {
    8. * rlim_t rlim_cur; //soft limit
    9. * rlim_t rlim_max; //hard limit
    10. * };
    11. *
    12. * int getrlimit(int resource, struct rlimit * rlim);
    13. * int setrlimit(int resource, const struct rlimit* rlim);
    14. * @return int
    15. */
    16. int main() {
    17. struct rlimit rlim;
    18. int ret;
    19. // 取得core文件大小的限制
    20. ret = getrlimit(RLIMIT_CORE, &rlim);
    21. if (ret == -1) {
    22. perror("getrlimit");
    23. return 1;
    24. }
    25. printf("before : RLIMIT_CORE limits: soft=%ld hard=%ld\n", rlim.rlim_cur, rlim.rlim_max);
    26. // 产生如下输出
    27. // RLIMIT_CORE limits: soft=0 hard=-1 -1表示无穷大
    28. rlim.rlim_cur = 32*1024*1024; //32MB
    29. rlim.rlim_max = RLIM_INFINITY;
    30. ret = setrlimit(RLIMIT_CORE, &rlim);
    31. if (ret == -1) {
    32. perror("setrlimit");
    33. return 1;
    34. }
    35. printf("setrlimit success!\n");
    36. ret = getrlimit(RLIMIT_CORE, &rlim);
    37. if (ret == -1) {
    38. perror("getrlimit");
    39. return 1;
    40. }
    41. printf("after: RLIMIT_CORE limits: soft=%ld hard=%ld\n", rlim.rlim_cur, rlim.rlim_max);
    42. }

    stat函数,获取文件元数据

    1. #include
    2. #include
    3. #include
    4. int stat(const char* path, struct stat* buf);
    5. int fstat(int fd, struct stat* buf);
    6. int lstat(const char* path, struct stat* buf);

     

     

     使用stat获取指定文件的大小

    1. #include
    2. #include
    3. #include
    4. #include
    5. int main(int argc, char* argv[]) {
    6. struct stat sb;
    7. int ret;
    8. if (argc < 2) {
    9. fprintf(stderr, "usage: %s \n", argv[0]);
    10. return 1;
    11. }
    12. ret = stat(argv[1], &sb);
    13. if (ret == -1) {
    14. perror("stat error");
    15. return 1;
    16. }
    17. printf("%s is %ld bytes\n", argv[1], sb.st_size);
    18. return 0;
    19. }

    下面这段代码会使用fstat检查一个已经打开的文件是否位于一个物理设备上

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. /**
    8. * @brief 如果fd位于一个物理设备上,则返回一个正整数,如果位于一个非物理或者虚拟设备上
    9. * 则返回0,发生错误,返回-1
    10. *
    11. * @param fd
    12. * @return int
    13. */
    14. int is_on_physical_device(int fd) {
    15. struct stat sb;
    16. int ret;
    17. ret = fstat(fd, &sb);
    18. if (ret == -1) {
    19. perror("fstat error");
    20. return -1;
    21. }
    22. return gnu_dev_major(sb.st_dev);
    23. }
    24. int main(int argc, char* argv[]) {
    25. struct stat sb;
    26. int ret;
    27. if (argc < 2) {
    28. fprintf(stderr, "usage: %s \n", argv[0]);
    29. return 1;
    30. }
    31. ret = stat(argv[1], &sb);
    32. if (ret == -1) {
    33. perror("stat error");
    34. return 1;
    35. }
    36. printf("%s is %ld bytes\n", argv[1], sb.st_size);
    37. int fd = open("buccaneer.txt", O_RDONLY);
    38. ret = is_on_physical_device(fd);
    39. if (ret == -1) {
    40. perror("is_on_physical_device faile\n");
    41. return -1;
    42. }
    43. if (ret == 0) {
    44. printf("buccaneer.txt is not on physical device!\n");
    45. } else {
    46. printf("buccaneer.txt is on physical device!\n");
    47. }
    48. return 0;
    49. }
    50. 输出:
    51. buccaneer.txt is 149 bytes
    52. buccaneer.txt is on physical device!

     获取文件使用权限

    1. #include
    2. #include
    3. int chmod(const char* path, mode_t mode);
    4. int fchmod(int fd, modt_t mode);

    将fd文件拥有者和组设定为root

    1. int make_root_owner(int fd) {
    2. int ret;
    3. // root的gid与uid皆为0
    4. ret = fchown(fd, 0, 0);
    5. if (ret)
    6. perror("fchown");
    7. return ret;
    8. }

  • 相关阅读:
    轨道交通行业网站(持续完善)
    一个页面从输入 URL 到页面加载显示完成,这个过程中都发生了什么?
    第 361 场 LeetCode 周赛题解
    UE5笔记【四】UE5主材质Master Materials和材质实例MI
    Hyperledger Fabric 2.x 自定义智能合约
    2.69分钟完成BERT训练!新发CANN 5.0加持
    idea+tomcat+mysql 从零开始部署Javaweb项目(保姆级别)
    【Excel】单元格如何设置可选项、固定表头
    ssm+vue基于微信小程序的捷邻生活便利购物超市商城系统#毕业设计
    Golang字符串和数组的相互转换
  • 原文地址:https://blog.csdn.net/wj617906617/article/details/133382416