Linux 多进程拷贝怎么写
时间: 2024-02-12 17:21:52 浏览: 28
在 Linux 中,可以使用多进程来实现文件拷贝。下面是一个简单的示例代码,展示了如何使用多进程进行文件拷贝:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define BUF_SIZE 4096
void copy_file(const char* source, const char* destination) {
int source_fd, dest_fd;
ssize_t bytes_read, bytes_written;
char buffer[BUF_SIZE];
// 打开源文件
source_fd = open(source, O_RDONLY);
if (source_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// 创建并打开目标文件
dest_fd = open(destination, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// 创建子进程
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// 子进程负责拷贝数据
while ((bytes_read = read(source_fd, buffer, BUF_SIZE)) > 0) {
bytes_written = write(dest_fd, buffer, bytes_read);
if (bytes_written != bytes_read) {
perror("write");
exit(EXIT_FAILURE);
}
}
if (bytes_read == -1) {
perror("read");
exit(EXIT_FAILURE);
}
// 关闭文件描述符
close(source_fd);
close(dest_fd);
exit(EXIT_SUCCESS);
} else {
// 父进程等待子进程结束
wait(NULL);
}
}
int main() {
const char* source = "source.txt";
const char* destination = "destination.txt";
copy_file(source, destination);
printf("文件拷贝完成!\n");
return 0;
}
```
在这个示例代码中,我们使用了`open()`函数打开源文件和目标文件,然后使用`fork()`创建了一个子进程。子进程负责从源文件中读取数据,并将数据写入目标文件中,而父进程则等待子进程结束。
需要注意的是,这只是一个简单的示例,可能有一些边界情况没有处理。如果需要在实际环境中使用,请根据实际需求进行适当的修改和完善。