在CentOS系统中,readdir函数用于读取目录中的文件和子目录。当多个进程或线程同时访问同一个目录时,可能会遇到并发访问的问题。为了处理这种情况,可以采用以下方法:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
int main() {
int fd = open("test_dir", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
// 使用flock实现文件锁
if (flock(fd, LOCK_EX) == -1) {
perror("flock");
close(fd);
return 1;
}
struct dirent *entry;
DIR *dp = opendir("test_dir");
if (dp == NULL) {
perror("opendir");
flock(fd, LOCK_UN);
close(fd);
return 1;
}
while ((entry = readdir(dp)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dp);
flock(fd, LOCK_UN);
close(fd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <pthread.h>
pthread_mutex_t lock;
void *read_dir(void *arg) {
char *dir = (char *)arg;
struct dirent *entry;
DIR *dp = opendir(dir);
if (dp == NULL) {
perror("opendir");
return NULL;
}
pthread_mutex_lock(&lock);
while ((entry = readdir(dp)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dp);
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t tid1, tid2;
pthread_mutex_init(&lock, NULL);
pthread_create(&tid1, NULL, read_dir, "test_dir");
pthread_create(&tid2, NULL, read_dir, "test_dir");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&lock);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <semaphore.h>
#include <pthread.h>
sem_t sem;
void *read_dir(void *arg) {
char *dir = (char *)arg;
struct dirent *entry;
DIR *dp = opendir(dir);
if (dp == NULL) {
perror("opendir");
return NULL;
}
sem_wait(&sem);
while ((entry = readdir(dp)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dp);
sem_post(&sem);
return NULL;
}
int main() {
pthread_t tid1, tid2;
sem_init(&sem, 0, 1); // 初始化信号量,初始值为1
pthread_create(&tid1, NULL, read_dir, "test_dir");
pthread_create(&tid2, NULL, read_dir, "test_dir");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
sem_destroy(&sem);
return 0;
}
这些方法可以帮助您在CentOS系统中处理readdir函数的并发访问问题。在实际应用中,请根据您的需求选择合适的方法。