PS:多进程拷贝文件--->(多进程拷贝文件-CSDN博客)
要求如下
创建两个线程thread1和thread2拷贝同一个文件,thread1拷贝前一半,thread2拷贝后一半。
demo.c (编译 gcc demo.c -lpthread)
#include <head.h>
typedef struct _ARG
{
const char *srcfile;
const char *destfile;
int start;
int len;
} arg_t;
int get_file_len(const char *srcfile)
{
int srcfd;
if (-1 == (srcfd = open(srcfile, O_RDONLY)))
{
perror("open error");
exit(-1);
}
int len = lseek(srcfd, 0, SEEK_END);
close(srcfd);
return len;
}
int copy_file(const char *src, const char *dest, int start, int len)
{
char buff[16] = {0};
int ret, count;
int srcfd, destfd;
if (-1 == (srcfd = open(src, O_RDONLY)))
{
perror("open src error");
exit(-1);
}
if (-1 == (destfd = open(dest, O_WRONLY)))
{
perror("open dest error");
exit(-1);
}
lseek(srcfd, start, SEEK_SET);
lseek(destfd, start, SEEK_SET);
while (1)
{
if (-1 == (ret = read(srcfd, buff, sizeof(buff))))
{
perror("read error");
exit(-1);
};
if (len < sizeof(buff))
{
write(destfd, buff, len);
break;
}
else
{
write(destfd, buff, ret);
}
len -= ret;
}
close(srcfd);
close(destfd);
return 0;
}
int init_file(const char *destfile)
{
int fd;
if (-1 == (fd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0666)))
{
perror("open error");
exit(-1);
}
close(fd);
return 0;
}
void *thread1(void *args)
{
// 子线程1拷贝前一半
arg_t args1;
args1 = *(arg_t *)args;
copy_file(args1.srcfile, args1.destfile, args1.start, args1.len);
printf("子线程1拷贝前一半完成...\n");
}
void *thread2(void *args)
{
// 子线程2拷贝后一半
arg_t args2;
args2 = *(arg_t *)args;
copy_file(args2.srcfile, args2.destfile, args2.start, args2.len);
printf("子线程2拷贝后一半完成...\n");
}
int main(int argc, const char *argv[])
{
// 入参合理性检查
if (argc != 3)
{
printf("usage error:%s srcfile destfile\n", argv[0]);
exit(-1);
}
// 创建两个线程
pthread_t pid1, pid2;
int fd;
int len;
init_file(argv[2]);
len = get_file_len(argv[1]);
arg_t argg[] = {
[0] = {argv[1], argv[2], 0, len / 2},
[1] = {argv[1], argv[2], len / 2, (len-(len/2))}};
if (errno = (pthread_create(&pid1, NULL, thread1, (void *)&argg[0])) != 0)
{
perror("pthread_create error");
exit(-1);
}
if (errno = (pthread_create(&pid2, NULL, thread2, (void *)&argg[1])) != 0)
{
perror("pthread_create error");
exit(-1);
}
// 主线程
pthread_join(pid1, NULL);
pthread_join(pid2, NULL);
return 0;
}