zoukankan      html  css  js  c++  java
  • APUE习题8.7

      看书的时候发现这个习题没有答案,于是就想把自己做的结果贴上来,和大家分享分享!

      首先把题目贴上来吧:

    /***********
    8.10节中提及POSIX.1要求在调用exec时关闭打开的目录流。按下列方法对此进行验证,对根目录调用opendir,查看在你的系统上实现的DIR结构,然后打印执行时关闭标志。接着open同一目录读取并打印执行时关闭标志
    ***********/

      首先说,关于执行时关闭标志的作用,JesseEisen的这篇博客已经讲解的非常好了,(传送门在这里)我就不在这里献丑了,我想讲的是opendir和open函数的一点区别。

      opendir函数在打开目录流的的时候是设置了close-on-exec(执行时关闭)标志的,open函数则没有。

      具体来看这段代码:

     1 /***
     2 这里的err_exit()函数是我自己定义的,功能就是调用strerror()函数打印出错误信息,并且调用exit()函数退出!
     3 ***/
     4 
     5 #include<dirent.h>
     6 #include<errno.h>
     7 #include<fcntl.h>
     8 #include<string.h>
     9 #include<stdlib.h>
    10 #include<stdarg.h>
    11 #include<stdio.h>
    12 #include<sys/types.h>
    13 #include<unistd.h>
    14 void err_exit(char *fmt,...);
    15 int main(int argc,char *argv[])
    16 {
    17     DIR *dirp;
    18     int dir_fd;
    19     int val;
    20 
    21     /*用opendir的方式打开目录,并且获取文件描述符,然后查看其close-on-exec标志*/
    22     if(NULL == (dirp=opendir("/")))
    23     err_exit("[opendir]: ");
    24     if(-1 == (dir_fd=dirfd(dirp)))  //获取打开目录流的文件描述符
    25     err_exit("[dirfd]: ");
    26     if(-1 == (val=fcntl(dir_fd,F_GETFD)))
    27     err_exit("[fcntl]: ");
    28 
    29     printf("%-9s: ","[opendir]");
    30     if(val & FD_CLOEXEC)
    31     printf("close-on-exec flag is on
    ");
    32     else
    33     printf("close-on-exec flag is off
    ");
    34 
    35     if(-1 == closedir(dirp))
    36     err_exit("[closedir]: ");
    37 
    38     /*用open的方式打开目录,然后查看其close-on-exec标志*/
    39     if(-1 == (dir_fd=open("/",O_DIRECTORY)))    //open函数加上O_DIRECTORY标志就能够打开目录了
    40     err_exit("[open]: ");
    41     if(-1 == (val=fcntl(dir_fd,F_GETFD)))
    42     err_exit("[fcntl]: ");
    43 
    44     printf("%-9s: ","[open]");
    45     if(val & FD_CLOEXEC)
    46     printf("close-on-exec flag is on
    ");
    47     else
    48     printf("close-on-exec flag is off
    ");
    49 
    50     if(-1 == close(dir_fd))
    51     err_exit("[close]: ");
    52 
    53     return 0;
    54 }

      这段代码功能就是这样的:

      首先通过opendir函数打开一个目录,然后通过dirfd函数提取出目录流的文件描述符,然后再利用fcntl获取close-on-exec标志。

      接着再来通过open函数(增加了O_DIRECTORY标志就能打开目录了,详见open(2))打开同一个目录,然后再来通过fcntl函数来查看它的close-on-exec标志。

      程序的运行结果如下:

      

      从结果中我们可以看到,opendir打开的目录流拥有close-on-exec标志位,而open函数打开的目录流没有close-on-exec标志位,这正好印证了APUE8.10节的叙述:

      

  • 相关阅读:
    d3-tree 双向树
    .gitignore
    url正则匹配
    this 指向
    git 用法小总结
    心态崩了?
    内存溢出和内存泄漏的区别
    jQuery添加方法
    物理像素与逻辑像素
    服务器返回的status
  • 原文地址:https://www.cnblogs.com/bwangel23/p/4297722.html
Copyright © 2011-2022 走看看