创建3个线程,一个子线程拷贝文件的前一半,一个子线程拷贝后一半文件。
#include<stdio.h>
#include<string.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void *fun1(void *a)
{
int len=*(int *)a;
int fd1=open("./1.txt",O_RDONLY);
char buff[1024];
int fd2=open("./2.txt",O_CREAT|O_WRONLY|O_TRUNC,0664);
read(fd1,buff,len/2);
write(fd2,buff,len/2);
close(fd1);
close(fd2);
return NULL;
}
void *fun2(void *a)
{
int len=*(int *)a;
int fd1=open("./1.txt",O_RDONLY);
char buff[1024];
int fd2=open("./3.txt",O_CREAT|O_WRONLY|O_TRUNC,0664);
lseek(fd1,len/2,SEEK_SET);
read(fd1,buff,len-len/2);
write(fd2,buff,len-len/2);
close(fd1);
close(fd2);
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t pt,pt2;
int fd1;
fd1=open("./1.txt",O_RDONLY);
int len=lseek(fd1,0,SEEK_END);
int k=pthread_create(&pt,NULL,fun1,&len);
int k1=pthread_create(&pt2,NULL,fun2,&len);
if(k!=0)
{
perror("k");
return -1;
}
if(k1!=0)
{
perror("k1");
return -1;
}
usleep(2);
pthread_join(pt,NULL);
pthread_join(pt2,NULL);
close(fd1);
return 0;
}