主题:求解:想写个用mmap实现多线程拷贝的程序,
刚刚学的多线程,还不是特熟。我是想在当前目录下实现文件拷贝,思路是这样:mmap创建两个映射区,分别对应源文件和目标文件。准备使用5个线程实现拷贝,线程创建时传入线程的编号(第几个),用于决定每个线程拷贝多少字节。在线程函数里对mmap映射区操作,我现在运行是段错误。。。gdb又不太会调。。。愁死我了。。。
下面是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#define THD 5
char *src,*tar;
int len,m,n;
void err_sys(char *str)
{
perror(str);
exit (1);
}
void *tfn(void *arg)
{
int i,num = (int)arg;
char *l,*r;
l = src;
r = tar;
l += num * m;
r += num * m;
if(num != THD - 1)
{
for(i = 0; i < m; i++)
*(r + i) = *(l + i);
}
else
{
for(i = 0; i < n; i++)
*(r + i) = *(l + i);
}
return NULL;
}
int main(int argc, char **argv)
{
int op,ip,i,err;
pthread_t tid[THD];
if(argc != 3)
err_sys("Input Error");
ip = open(argv[1],O_RDONLY);
if(ip < 0)
err_sys("open failed");
op = open(argv[2],O_RDWR | O_CREAT | O_TRUNC,0644);
if(op < 0)
err_sys("open failed");
len = lseek(ip,0,SEEK_END);
m = len / THD; n = len - (THD - 1) * m;
lseek(op,len - 1, SEEK_SET);
write(op, "a", 1);
src = (char*)mmap(NULL, len, PROT_READ, MAP_SHARED, ip, 0);
if(src == MAP_FAILED)
err_sys("mmap failed");
tar = (char*)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, op, 0);
if(tar == MAP_FAILED)
err_sys("mmap failed");
close(ip);
close(op);
tid = (pthread_t *)malloc(sizeof(pthread_t) * THD);
for(i = 0; i < THD; i++)
{
if ((err = pthread_create(&tid[i],NULL,tfn,(void*)i)) != 0)
err_sys("- -! --> thread failed!");
}
for(i = 0; i < THD; i++)
pthread_join(tid[i], NULL);
munmap(src,len);
munmap(tar,len);
return 0;
}
下面是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#define THD 5
char *src,*tar;
int len,m,n;
void err_sys(char *str)
{
perror(str);
exit (1);
}
void *tfn(void *arg)
{
int i,num = (int)arg;
char *l,*r;
l = src;
r = tar;
l += num * m;
r += num * m;
if(num != THD - 1)
{
for(i = 0; i < m; i++)
*(r + i) = *(l + i);
}
else
{
for(i = 0; i < n; i++)
*(r + i) = *(l + i);
}
return NULL;
}
int main(int argc, char **argv)
{
int op,ip,i,err;
pthread_t tid[THD];
if(argc != 3)
err_sys("Input Error");
ip = open(argv[1],O_RDONLY);
if(ip < 0)
err_sys("open failed");
op = open(argv[2],O_RDWR | O_CREAT | O_TRUNC,0644);
if(op < 0)
err_sys("open failed");
len = lseek(ip,0,SEEK_END);
m = len / THD; n = len - (THD - 1) * m;
lseek(op,len - 1, SEEK_SET);
write(op, "a", 1);
src = (char*)mmap(NULL, len, PROT_READ, MAP_SHARED, ip, 0);
if(src == MAP_FAILED)
err_sys("mmap failed");
tar = (char*)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, op, 0);
if(tar == MAP_FAILED)
err_sys("mmap failed");
close(ip);
close(op);
tid = (pthread_t *)malloc(sizeof(pthread_t) * THD);
for(i = 0; i < THD; i++)
{
if ((err = pthread_create(&tid[i],NULL,tfn,(void*)i)) != 0)
err_sys("- -! --> thread failed!");
}
for(i = 0; i < THD; i++)
pthread_join(tid[i], NULL);
munmap(src,len);
munmap(tar,len);
return 0;
}