在多線程環境下使用 copirdir
函數,需要考慮線程安全和同步問題。copirdir
是一個用于復制目錄及其內容的函數,通常在 POSIX 系統上可用。以下是一個基本的示例,展示如何在多線程環境中安全地使用 copirdir
。
首先,確保你有一個線程安全的 copirdir
實現。你可以使用 POSIX 線程(pthreads)庫來實現這一點。以下是一個簡單的示例代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <pthread.h>
// 線程安全的全局變量
pthread_mutex_t lock;
// 復制文件或目錄的函數
int copy_item(const char *src, const char *dest) {
struct stat st;
if (stat(src, &st) == -1) {
perror("stat");
return -1;
}
if (S_ISDIR(st.st_mode)) {
// 創建目標目錄
if (mkdir(dest, st.st_mode) == -1) {
perror("mkdir");
return -1;
}
// 打開源目錄
DIR *dir = opendir(src);
if (!dir) {
perror("opendir");
return -1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char src_path[1024], dest_path[1024];
snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name);
snprintf(dest_path, sizeof(dest_path), "%s/%s", dest, entry->d_name);
// 遞歸復制子目錄或文件
if (copy_item(src_path, dest_path) != 0) {
closedir(dir);
return -1;
}
}
closedir(dir);
} else {
// 復制文件
FILE *src_file = fopen(src, "rb");
if (!src_file) {
perror("fopen");
return -1;
}
FILE *dest_file = fopen(dest, "wb");
if (!dest_file) {
perror("fopen");
fclose(src_file);
return -1;
}
char buffer[1024];
size_t bytes_read;
while ((bytes_read = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
if (fwrite(buffer, 1, bytes_read, dest_file) != bytes_read) {
perror("fwrite");
fclose(src_file);
fclose(dest_file);
return -1;
}
}
fclose(src_file);
fclose(dest_file);
}
return 0;
}
// 線程函數
void *thread_func(void *arg) {
const char *src = (const char *)arg;
const char *dest = "destination_directory"; // 目標目錄
pthread_mutex_lock(&lock);
if (copy_item(src, dest) != 0) {
fprintf(stderr, "Failed to copy directory: %s\n", src);
}
pthread_mutex_unlock(&lock);
return NULL;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <source_directory>\n", argv[0]);
return 1;
}
const char *src_dir = argv[1];
// 初始化互斥鎖
if (pthread_mutex_init(&lock, NULL) != 0) {
perror("pthread_mutex_init");
return 1;
}
// 創建線程
pthread_t thread;
if (pthread_create(&thread, NULL, thread_func, (void *)src_dir) != 0) {
perror("pthread_create");
pthread_mutex_destroy(&lock);
return 1;
}
// 等待線程結束
pthread_join(thread, NULL);
// 銷毀互斥鎖
pthread_mutex_destroy(&lock);
return 0;
}
在這個示例中,我們使用了一個互斥鎖 pthread_mutex_t
來確保在多線程環境下對 copy_item
函數的調用是線程安全的。每個線程在調用 copy_item
之前都會鎖定互斥鎖,并在調用完成后解鎖。
請注意,這個示例假設目標目錄已經存在。如果目標目錄不存在,你需要在程序開始時創建它,或者在 copy_item
函數中添加創建目標目錄的邏輯。
編譯這個程序時,你需要鏈接 pthread 庫:
gcc -o copirdir_example copirdir_example.c -lpthread
運行這個程序時,傳入源目錄作為參數:
./copirdir_example source_directory
這個程序會在目標目錄中復制源目錄及其內容。