双线程拷贝
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#define BUFFER_SIZE 1024
int main() {
FILE *sourceFile, *destFile;
char buffer[BUFFER_SIZE];
size_t fileSize, halfSize1, halfSize2;
__pid_t childPid;
if (!(sourceFile = fopen("source.txt", "r"))) {
printf("Failed to open source file.\n");
return 1;
}
fseek(sourceFile, 0, SEEK_END);
fileSize = ftell(sourceFile);
halfSize1 = fileSize / 2;
halfSize2 = halfSize1 + fileSize % 2;
rewind(sourceFile);
destFile = fopen("destination.txt", "w");
if (destFile == NULL) {
printf("Failed to create destination file.\n");
fclose(sourceFile);
return 1;
}
childPid = fork();
if (childPid < 0) {
printf("Failed to create child process.\n");
fclose(sourceFile);
fclose(destFile);
return 1;
} else if (childPid == 0) {
fread(buffer, halfSize1, 1, sourceFile);
fwrite(buffer, halfSize1, 1, destFile);
} else {
fseek(sourceFile, halfSize1, SEEK_SET);
fread(buffer, halfSize2, 1, sourceFile);
fwrite(buffer, halfSize2, 1, destFile);
wait(NULL);
}
fclose(sourceFile);
fclose(destFile);
return 0;
}
结果