线程 19

 创建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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值