1. 使用多进程完成两个文件的拷贝,父进程拷贝前一半,子进程拷贝后一半,父进程回收子进程的资源
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAXSIZE 1024
int main(int argc, char const *argv[])
{
pid_t pid = fork();
if (0 == pid)
{
usleep(100000);
}
// 区分父子进程打开 dest 的方式
int src = -1, dest = -1;
src = open("pm.bmp", O_RDONLY);
if (0 != pid)
{
dest = open("pm2.bmp", O_WRONLY|O_CREAT|O_TRUNC, 0664);
}
else
{
dest = open("pm2.bmp", O_RDWR|O_APPEND|O_CREAT);
}
if (-1 == src || -1 == dest)
{
perror("open error");
return -1;
}
// timer
struct timespec start_time = { 0, 0 }, end_time = { 0, 0 };
timespec_get(&start_time, TIME_UTC);
// 计算文件长度,控制光标位置
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);
}
// timer,计算复制所用时间 (ns)
timespec_get(&end_time, TIME_UTC);
printf("pid:%d, time:%ld\n", pid, end_time.tv_nsec - start_time.tv_nsec);
if (0 == pid)
{
exit(0);
}
// 等待回收子进程资源
wait(NULL);
close(src);
close(dest);
return 0;
}