我正試圖編寫一個程序,將多個文件備份到名爲.backups的文件夾中。它爲每個文件或子目錄創建一個線程,並且該線程負責複製操作。但它不能正常工作。有時文件不會被複制,有時它們會有0個字節,有時它可以正常工作。它看起來完全是隨機的,我不知道是什麼導致了它。任何人都可以幫我弄明白嗎?線程安全文件副本
// Copies the file from source to destination and returns number of bytes written
ssize_t copy_file(char* from, char *to)
{
const int BUFFER_SIZE = 4096;
char buffer[BUFFER_SIZE];
ssize_t n;
ssize_t written = 0;
FILE* file_from = fopen(from, "r");
FILE* file_to = fopen(to, "w");
if (file_from == NULL || file_to == NULL)
return -1;
while ((n = fread(buffer, 1, BUFFER_SIZE, file_from)) > 0) {
if (fwrite(buffer, sizeof(char), n, file_to) != n)
return -1;
written += n;
}
return written;
}
// Thread responsible for handling the backup of a single file or subdirectory
void* backup_thread(void* arg)
{
struct backup_info* info = (struct backup_info*) arg;
ssize_t written;
written = copy_file(info->file, info->destination);
int rc = pthread_detach(pthread_self());
if (rc != 0)
exit(EXIT_FAILURE);
free(info);
return NULL;
}
編輯:另外,這是我如何創建每個線程。
struct backup_info* info = malloc(sizeof(struct backup_info));
if ((rc = pthread_create(&thread_id, NULL, backup_thread, info)) != 0)
fprintf(stderr, "pthread_create() failed (%d): %s", rc, strerror(rc));
只要你不使用全局變量,你的函數應該是可重入的。如何使用互斥鎖? – 2015-04-06 01:21:43
我在哪裏添加這個互斥體? – Ryan 2015-04-06 01:27:19
'copy_file'的開始和結束。 – 2015-04-06 01:30:57