ReadDir()线程不安全函数

一、readdir函数:      

struct dirent *readdir(DIR *dirp); 

The  data  returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream.

成功时,readdir() 返回指向 dirent 结构的指针。(这个结构是静态分配的;不要试图去free(3) 它。)如果到达了上当结尾,NULL 被返回并保持ERRNO不变。如果错误发生了,NULL 被返回并小心设置 ERRNO值。

readdir函数为非线程安全函数;

解决方法:

1、加锁;

2、用局部变量保存数据。

二、线程不安全函数 

多线程不安全函数是指:
一个进程中有很多全局变量以及函数(error、strtok、asctime等),各个线程对这些变量会产生干扰。在多线程运行期库中每个线程有自己的本地存储空间,有时也会使用全局变量和静态变量,如果多线程随意同时访问全局变量和静态变量,就将出现意向不到的错误,这个在现在的多线程编程中一般都会通过加锁等机制解决,但我们往往忽略了C run-time library里面的一些函数使用了全局变量和静态变量却没用相应机制避免冲突。

而readdir函数因为内部使用了静态数据,即readdir成功时返回指针所指向的dirent结构体是静态分配的,所以readdir被认为不是线程安全的函数,POSIX[i]标准这样描述:

         The application shall not modify the structure to which the return value of readdir() points, nor any storage areas pointed to by pointers within the structure. The returned pointer, and pointers within the structure, might be invalidated or the structure or the storage areas might be overwritten by a subsequent call to readdir() on the same directory stream. They shall not be affected by a call to readdir() on a different directory stream.

         If a file is removed from or added to the directory after the most recent call to opendir() or rewinddir(),whether a subsequent call to readdir() returns an entry for that file is unspecified.

         The readdir() function need not be thread-safe.

解决方法可以采用局部变量保存数据,也可以加锁使用;当然还可以使用readdir_r函数(然而,在GNU的官方文档[ii]中还是建议使用readdir函数)。

猜你喜欢

转载自blog.csdn.net/linuxwln/article/details/81565009
今日推荐