使用READDIR和多线程下的READDIR_R读取目录

书上只说了用第一个函数在多线程下会不安全,

为什么不安全,也没有说,只是取嘛,现在想不太通。

是为记。。

 1 [root@localhost ccode]# cat readdir_exp.c 
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <dirent.h>
 5 
 6 int main(int argc, char *argv[])
 7 {
 8     DIR *dirp;
 9     struct dirent *dp;
10     dirp = opendir(argv[1]);
11     while((dp = readdir(dirp)) != NULL)
12     {
13         if(dp->d_name[0] == '.')
14             continue;
15         printf("inode = %d\t", dp->d_ino);
16         printf("reclen = %d\t", dp->d_reclen);
17         printf("name = %s\n", dp->d_name);
18     }
19     closedir(dirp);
20     return 0;
21 }
 1 [root@localhost ccode]# cat readdir_r_exp.c 
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <dirent.h>
 5 
 6 int main(void)
 7 {
 8     DIR *dirp;
 9     struct dirent *dp1 = malloc(sizeof(struct dirent));
10     struct dirent *dp2 = malloc(sizeof(struct dirent));
11     dirp = opendir(".");
12     while(1)
13     {
14         if((readdir_r(dirp, dp1, &dp2)) != 0)
15         {
16             perror("readdir");
17             exit(EXIT_FAILURE);
18         }
19         if(dp2 == NULL)
20             break;
21         if(dp2->d_name[0] == '.')
22             continue;
23         printf("inode = %d\t", dp2->d_ino);
24         printf("reclen = %d\t", dp2->d_reclen);
25         printf("name = %s\n", dp2->d_name);
26     }
27     closedir(dirp);
28     free(dp1);
29     free(dp2);
30     return 0;
31 }

我试过了,输出都一样的。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值