APUE习题8.7

时间:2023-03-09 16:34:22
APUE习题8.7

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

  首先把题目贴上来吧:

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

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

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

  具体来看这段代码:

 /***
这里的err_exit()函数是我自己定义的,功能就是调用strerror()函数打印出错误信息,并且调用exit()函数退出!
***/ #include<dirent.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<stdarg.h>
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
void err_exit(char *fmt,...);
int main(int argc,char *argv[])
{
DIR *dirp;
int dir_fd;
int val; /*用opendir的方式打开目录,并且获取文件描述符,然后查看其close-on-exec标志*/
if(NULL == (dirp=opendir("/")))
err_exit("[opendir]: ");
if(- == (dir_fd=dirfd(dirp))) //获取打开目录流的文件描述符
err_exit("[dirfd]: ");
if(- == (val=fcntl(dir_fd,F_GETFD)))
err_exit("[fcntl]: "); printf("%-9s: ","[opendir]");
if(val & FD_CLOEXEC)
printf("close-on-exec flag is on\n");
else
printf("close-on-exec flag is off\n"); if(- == closedir(dirp))
err_exit("[closedir]: "); /*用open的方式打开目录,然后查看其close-on-exec标志*/
if(- == (dir_fd=open("/",O_DIRECTORY))) //open函数加上O_DIRECTORY标志就能够打开目录了
err_exit("[open]: ");
if(- == (val=fcntl(dir_fd,F_GETFD)))
err_exit("[fcntl]: "); printf("%-9s: ","[open]");
if(val & FD_CLOEXEC)
printf("close-on-exec flag is on\n");
else
printf("close-on-exec flag is off\n"); if(- == close(dir_fd))
err_exit("[close]: "); return ;
}

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

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

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

  程序的运行结果如下:

  APUE习题8.7

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

  APUE习题8.7