书上只说了用第一个函数在多线程下会不安全,
为什么不安全,也没有说,只是取嘛,现在想不太通。
是为记。。
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 }
我试过了,输出都一样的。。
时间: 2024-10-31 23:14:52