【发布时间】:2020-07-21 23:47:03
【问题描述】:
我正在学习 stat 和 readlink 等系统调用。我尝试以两种不同的方式统计根目录:
- 只需统计到根目录的路径。很简单。
- 然后,绕道而行,fopen“/”,从我得到的 fd 中创建一个文件描述符路径,然后将其读取链接以获取“/”。然后统计。
我不明白这是我期望的工作方式,并且 inode 编号是相同的,除了当我在之后引入更多代码时,即 getcwd,inode 奇怪地不一样并且测试 2 失败。如果你同时运行这两个版本,不管有没有它说要删掉的部分,p2 的 printf 也会改变,你可以看到/ 之后有垃圾。我在这里做错了什么或这里发生了什么?这些初始语句之后的代码如何导致代码中的早期更改?
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
int main()
{
/* Stat root this way */
struct stat st1;
char *p1 = "/";
if (!stat(p1, &st1))
printf("PASS\n");
else
printf("FAIL - %m\n");
/* Stat root another way */
struct stat st2;
char fdpath[100], p2[100];
FILE *fp = fopen("/", "r");
sprintf(fdpath, "/proc/self/fd/%d", fileno(fp));
readlink(fdpath, p2, sizeof(p2));
if (!stat(p2, &st2))
printf("PASS\n");
else
printf("FAIL - %m\n");
printf("p2 = %s\n", p2);
/* Check inodes are the same */
printf(" st1.st_ino = %ld\n", st1.st_ino);
printf(" st2.st_ino = %ld\n", st2.st_ino);
/* TRY WITHOUT THIS - Adding this makes the inodes different! Take it out and they're the same */
char cwd_buf[100];
char *cwd_ret = getcwd(cwd_buf, sizeof(cwd_buf));
if (cwd_ret == NULL)
printf("getcwd failed - %m\n");
printf("cwd_ret = %s\n", cwd_ret);
return 0;
}
【问题讨论】:
-
@LHLaurini,我注意到用
!检查0是否成功了吗? -
你是对的。哎呀。
-
如果您在适当的地方
fclose(fp)会发生什么? (就像你应该作为一个正直的软件公民一样。) -
请不要在致电
printf()时使用%m -
关于:
if (cwd_ret == NULL) printf("getcwd failed\n"); printf("cwd_ret = %s\n", cwd_ret);getcwd()调用失败时,不要尝试打印调用结果(这是一个NULL指针)