Unix环境高级编程上的一道课后习题 也是一道面试题
the original question:
Does the UNIX System have a fundamental limitation on the depth of a directory tree? To find
out, write a program that creates a directory and then changes to that directory, in a loop.
Make certain that the length of the absolute pathname of the leaf of this directory is
greater than your system's PATH_MAX limit. Can you call getcwd to fetch the directory's
pathname? How do the standard UNIX System tools deal with this long pathname? Can you
archive the directory using either tar or cpio?
translate:
UNIX系统的目录树有没有深度上的限制?在一个循环中创建一个目录并且进入到那个目录,写这样的程序
来验证。确认目录分支的绝对路径长度大于系统定义的PATH_MAX限制。你能否调用getcwd去获取此目录的
路径?标准UNIX系统工具是怎么处理这种长路径的?你能否使用tar或cpio访问此目录?
doubt:
1.系统的PATH_MAX限制是多少?PATH_MAX是指目录深度,还是指路径字符串长度?
2.处理长路径的工具有哪些?
3.cpio是什么命令?
cpio是一个备份工具,具体的可以通过man cpio来获取帮助.
testing program:
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
// (part 1.)
// if the PATH_MAX is the depth of the directory tree.
#define PATH_TEST (PATH_MAX+1)
int mian(void)
{
int depth = 0;
char pathname[PATH_MAX*4];
char temp[PATH_MAX*4];
printf("the PATH_MAX's value is %d./n", PATH_MAX);
while(depth++ < PATH_TEST)
{
sprintf(temp, "//%d", depth);
strcat(pathname, temp);
ret = mkdir(pathname, 777);
if (ret == -1)
{
printf("the max depth is %d./n", depth);
printf("the failed pathname is /"%s/"./n", pathname);
break;
}
}
return 1;
}
// (part 2.)
// if the PATH_MAX is the length of the directory pathname.
#define PATH_TEST (PATH_MAX*2)
int main(void)
{
int length = 0;
int depth = 0;
char pathname[PATH_TEST];
char temp[PATH_TEST];
printf("the PATH_MAX's value is %d./n", PATH_MAX);
while(length < PATH_TEST)
{
sprintf(temp, "//%d", depth++);
strcat(pathname, temp);
length = strlen(pathname);
ret = mkdir(pathname, 777);
if (ret == -1)
{
printf("the max depth is %d./n", depth);
printf("the max length is %d./n", length);
printf("the failed pathname is /"%s/"./n", pathname);
break;
}
}
return 1;
}
additional requirement:
2. shell脚本的程序:
path=./
count=1
while [ 1 ]
do
path=$path/1234567890
count=` expr $count + 1 `
echo $count
mkdir $path
if [ ! $? -eq 0 ]
then
break
fi
count是间目录的深度,1234567890是目录名,一层一层往下建,有的机器上可以建378层.
PATH_MAX=4096,为路径字符串长度。
但可以在控制台命令行环境下进入到最底层,建立下级目录,此时目录绝对路径字符串长度已经超过PATH_MAX。
内核对目录的深度没有内在的限制,但是如果路径名的长度超出了PATH_MAX,则有许多命令会失败.