多进程实现拷贝
#include <myhead.h>
//定义结构体
typedef struct INFO
{
const char *src_file;
const char *dest_file;
int mv;
int size;
}info_t;
//获取源文件的大小并且创建目标文件
int size_creat(const char *src_file,const char *dest_file)
{
//获取源文件的大小(字节)
int src_fd = open(src_file,O_RDONLY);
if(-1 == src_fd)
{
perror("open error");
return -1;
}
int size = lseek(src_fd,0,SEEK_END);
close(src_fd);
//创建目标文件
int dest_fd = open(dest_file,O_WRONLY | O_CREAT | O_TRUNC,0666);
if(-1 == dest_fd)
{
perror("open error");
return -1;
}
close(dest_fd);
return size;
}
//复制源文件内容到目标文件内容中
void *cp(void *arg)
{
//强制类型转换
info_t info = *(info_t *)arg;
int src_fd = 0;
int dest_fd = 0;
//打开源文件
if(-1 == (src_fd = open(info.src_file,O_RDONLY)))
{
perror("open error");
pthread_exit(NULL);
}
//打开目标文件
if(-1 == (dest_fd = open(info.dest_file,O_WRONLY)))
{
perror("open error");
pthread_exit(NULL);
}
//定位光标
lseek(src_fd,info.mv,SEEK_SET);
lseek(dest_fd,info.mv,SEEK_SET);
int ret = 0;
int num = 0;
char buf[64] = {0};
while (1)
{
ret = read(src_fd,buf,sizeof(buf));
if(0 == ret)
{
break;
}
num += ret;
if(num > info.size)
{
write(dest_fd,buf,info.size - (num - ret));
break;
}
write(dest_fd,buf,ret);
}
//关闭文件
close(src_fd);
close(dest_fd);
}
int main(int argc, char const *argv[])
{
if(3 != argc)
{
printf("Usage : %s src_file dest_file\n",argv[0]);
return -1;
}
int size = 0;
size = size_creat(argv[1],argv[2]);
//线程1复制文件内容的前一半
//线程2复制文件内容的后一半
info_t arg[2] = {
{argv[1],argv[2],0,size/2},
{argv[1],argv[2],size/2,size - size/2}
};
pthread_t thread1 = 0;
pthread_t thread2 = 0;
int ret = 0;
//创建线程1
if(0 != (ret = pthread_create(&thread1,NULL,cp,&arg[0])))
{
printf("pthread_create error : errno = [%d] errstr = [%s]\n",ret,strerror(ret));
exit(EXIT_FAILURE);
}
//创建线程2
if(0 != (ret = pthread_create(&thread2,NULL,cp,&arg[1])))
{
printf("pthread_create error : errno = [%d] errstr = [%s]\n",ret,strerror(ret));
exit(EXIT_FAILURE);
}
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
使用多线程完成两个文件的拷贝,第一个线程拷贝前一半,第二个线程拷贝后一半,主线程关闭