求大侠帮忙看看多线程拷贝文件代码出错

mznxbc123456 2015-09-24 03:55:11
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<pthread.h>
#include<string.h>

#define SPATH "/root/Desktop/pthread/1G.rar"
#define DPATH "/root/Desktop/1G1.rar"
#define SIZE 1024
#define NUM_THREAD 5

int get_size(char *filename);
void* threadCp(void *arg);
int i_thread=0;

typedef struct Cp_INFO
{
int i_num;
}info;

int get_size(char *filename)
{
struct stat st;
memset(&st,0,sizeof(st));
stat(filename,&st);
return st.st_size;
}
void* threadCp(void *arg)
{
info info1=*((info*)arg);
int in=0;
int out=0;
int size=0;
int rlen=0;
char buffer[SIZE]={'\0'};
in=open(SPATH,O_RDONLY);
if(-1==in)
{
printf("Open File error!\n");
}
out=creat(DPATH,O_WRONLY);
if(-1==out)
{
printf("Create File error!\n");
}
size=get_size(SPATH);
printf("i_num=%d\n",info1.i_num);
printf("size*i_thread/NUM_THREAD=%d\n",size*i_thread/NUM_THREAD);
lseek(in,size*i_thread/NUM_THREAD,SEEK_SET);
lseek(out,size*i_thread/NUM_THREAD,SEEK_SET);
int len=0;
int total=0;
while((rlen=read(in,buffer,sizeof(buffer)))>0)
{
write(out,buffer,rlen);
total+=rlen;
if(total>size/NUM_THREAD)
{
break;
}
}
close(in);
close(out);
}

int main()
{
pthread_t pid[NUM_THREAD];
info c_info;
int i=0;
int j=0;
/*int out=creat(DPATH,S_IWUSR);
if(-1==out)
{
printf("Create File error!\n");
return -1;
}*/

for(i=0;i<NUM_THREAD;i++)
{
i_thread=i;
c_info.i_num=i;
printf("info_inum=%d\n",c_info.i_num);
pthread_create(&pid[i],NULL,threadCp,(void*)&c_info);
}

for(j=0;j<NUM_THREAD;j++)
{
pthread_join(pid[j],NULL);
}
printf("copy file finish!\n");
return 0;
}

这段代码运行后把一个1.2G的文件复制成314M样子的文件,看了很久没看出问题所在,请大侠帮忙看看问题在哪?小弟谢谢大家了
...全文
107 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
s1120132914 2015-10-14
  • 打赏
  • 举报
回复
为啥不用pread()和pwrite()
ssize_t pread(int fd, void *buf, size_t count, off_t pos);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t pos);
  • 打赏
  • 举报
回复
这个应该是要加线程锁
mznxbc123456 2015-09-25
  • 打赏
  • 举报
回复
引用 3 楼 q3733353520 的回复:
[quote=引用 2 楼 mznxbc123456 的回复:] [quote=引用 1 楼 q3733353520 的回复:] 这个应该是要加线程锁
现在已经加了,但出现问题,拷贝700M文件没问题,但文件超过1G就出错。那线程改成1拷贝就没问题。[/quote] 代码贴出来看看[/quote] 已经搞定了
  • 打赏
  • 举报
回复
引用 2 楼 mznxbc123456 的回复:
[quote=引用 1 楼 q3733353520 的回复:] 这个应该是要加线程锁
现在已经加了,但出现问题,拷贝700M文件没问题,但文件超过1G就出错。那线程改成1拷贝就没问题。[/quote] 代码贴出来看看
mznxbc123456 2015-09-25
  • 打赏
  • 举报
回复
引用 1 楼 q3733353520 的回复:
这个应该是要加线程锁
现在已经加了,但出现问题,拷贝700M文件没问题,但文件超过1G就出错。那线程改成1拷贝就没问题。

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧