代码:
#include<myhead.h>
#define MAXSIZE 1024
int main(int argc, char const *argv[])
{
pid_t pid = fork();
// 区分父子进程打开 dest 的方式
int src = -1, dest = -1;
src = open("aa1.bmp", O_RDONLY);
if (0 != pid)
{
dest = open("tt1.bmp", O_WRONLY|O_CREAT|O_TRUNC, 0664);
}
else
{
dest = open("tt1.bmp", O_RDWR|O_APPEND|O_CREAT);
}
if (-1 == src || -1 == dest)
{
perror("open error");
return -1;
}
// 计算文件长度,控制光标位置
int file_len = lseek(src, 0, SEEK_END);
lseek(src, 0, SEEK_SET);
if (0 == pid)
{
lseek(src, file_len / 2, SEEK_SET);
lseek(dest, file_len / 2, SEEK_SET);
}
// 复制
int len = 0, count = 0;
char buf[MAXSIZE];
int bufsize = sizeof(buf);
while (count < file_len / 2)
{
if (file_len / 2 - count < bufsize)
{
bufsize = file_len / 2 - count;
}
len = read(src, buf, bufsize);
write(dest, buf, len);
count += sizeof(buf);
}
wait(NULL);// 等待回收子进程资源
fclose(src);
fclose(dest);
return 0;
}
结果: