作业:多线程复制文件(简易版)---时间仓促。真正合理的应该是利用malloc 及线程列表多线程复制文件。那样比设置全局变量划算得多。但两三个线程而已,就无所谓
ubuntu@ubuntu:~$ cat test4.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pthread.h>
#include <fcntl.h>
#include <string.h>
int myread;
int mywrite;
int len;
pthread_t pid,pd1,pd2;
void copyfile(int myread,int mywrite,int pot,int len)//拷贝文件
{
char buf[128]={'\0'};
int count=0;
lseek(myread,pot,SEEK_SET);
lseek(mywrite,pot,SEEK_SET);
while(1)
{
int rdfil=read(myread,buf,sizeof(buf));
count=count+rdfil;
if(count>len ||rdfil==0)
{
write(mywrite,buf,rdfil-(count-len));
bzero(buf,sizeof(buf));
break;
}
write(mywrite,buf,rdfil);
bzero(buf,sizeof(buf));
}
}
void *task2(void *arg)
{
//拷贝后半段
copyfile(myread,mywrite,0,len/2);
pthread_exit(NULL);
}
void *task1(void *arg)
{
//拷贝前半段
copyfile(myread,mywrite,len/2,len-len/2);
pthread_exit(NULL);
}
void *task(void *arg)
{
if(pthread_create(&pd1,NULL,task1,&pid))
{
perror("Wrong");
exit(-1);
}
if(pthread_create(&pd2,NULL,task2,&pid))
{
perror("Wrong");
exit(-1);
}
}
pthread_join(pd1,NULL);
pthread_join(pd2,NULL);
int main(int argc,char *argv[])
{
if(argc!=3)
{
perror("参数错");
return -1;
}
myread=open(argv[1],O_RDONLY);
if(myread<0)
{
perror("Read Wrong");
return -1;
}
mywrite=open(argv[2],O_RDWR|O_TRUNC|O_CREAT,0664);
if(mywrite<0)
{
perror("open for write wrong");
return -1;
}
len=lseek(myread,0,SEEK_END);
if(pthread_create(&pid,NULL,task,NULL))
{
perror("open for write wrong");
return -1;
}
pthread_exit(NULL);
pthread_join(pid,NULL);
return 0;
}