#include <head.h>
#define N 4
int main(int argc, const char* argv[])
{
pid_t pid;
int fd, son_fd, far_fd, size, ret, value;
char buf[N] = { 0 };
fd = open("./text.txt", O_RDONLY);
if (fd == -1) {
PRINT_ERR("");
}
size = lseek(fd, 0, SEEK_END);
size = size / 2;
close(fd);
pid = fork();
if (pid == -1) {
PRINT_ERR("");
} else if (pid == 0) {
son_fd = open("./sonfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (son_fd == -1) {
PRINT_ERR("");
}
fd = open("./text.txt", O_RDONLY);
if (fd == -1) {
PRINT_ERR("");
}
lseek(fd, size + 1, SEEK_SET);
while ((value = read(fd, buf, sizeof(buf))) > 0) {
write(son_fd, buf, value);
}
close(fd);
close(son_fd);
} else {
far_fd = open("./farfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (far_fd == -1) {
PRINT_ERR("");
}
fd = open("./text.txt", O_RDONLY);
if (fd == -1) {
PRINT_ERR("");
}
while (size > 0) {
if (size > N) {
read(fd, buf, N);
write(far_fd, buf, N);
size -= N;
} else {
ret = read(fd, buf, size);
write(far_fd, buf, ret);
break;
}
}
close(fd);
close(far_fd);
}
return 0;
}
两个进程同时拷贝一个文件,把拷贝结果放在两个不同文件。
源文件text.txt
拷贝后的俩文件