创建3个进程,子进1程拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。
#include<myhead.h>
int main() {
int fd, fd1;
char buff[1024];
struct stat st;
int file_size;
pid_t pid;
// 获取源文件的大小
if (stat("1.txt", &st) == -1) {
perror("获取文件信息失败");
exit(1);
}
file_size = st.st_size;
// 打开源文件
fd = open("1.txt", O_RDONLY);
if (fd == -1) {
perror("打开源文件失败");
return -1;
}
// 创建第一个子进程
pid = fork();
if (pid == 0) {
// 子进程1:读取文件的前一半并写入目标文件
fd1 = open("2.txt", O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (fd1 == -1) {
perror("打开目标文件失败");
exit(EXIT_FAILURE);
}
read(fd, buff, file_size / 2);
write(fd1, buff, file_size / 2);
close(fd1);
exit(EXIT_SUCCESS);
} else if (pid > 0) {
// 父进程继续执行,创建第二个子进程
pid_t pid2 = fork();
if (pid2 == 0) {
// 子进程2:读取文件的后一半并写入目标文件
fd1 = open("2.txt", O_WRONLY);
if (fd1 == -1) {
perror("打开目标文件失败");
exit(EXIT_FAILURE);
}
lseek(fd, file_size / 2, SEEK_SET);
read(fd, buff, file_size - (file_size / 2));
write(fd1, buff, file_size - (file_size / 2));
close(fd1);
exit(EXIT_SUCCESS);
} else if (pid2 > 0) {
// 父进程等待两个子进程结束
wait(NULL);
wait(NULL);
printf("文件拷贝完成,子进程已回收。\n");
}
} else {
perror("fork失败");
exit(EXIT_FAILURE);
}
// 关闭源文件
close(fd);
return 0;
}