使用两个线程完成两个文件的拷贝,分支线程1拷贝前一半,分支线程2拷贝后一半,主线程回收两个分支线程的资源
代码:
/*******************************************/
文件名:threadwork.c
/*******************************************/
#include <myhead.h>
//创建传输信息的结构体
struct TXT
{char *a;char *b;int key;
};
//定义求源文件大小的函数
int get_file_len(const char *srcfile, const char *destfile)
{//以只读的形式打开源文件int sfd = open(srcfile, O_RDONLY);if (sfd == -1){perror("open srcfile error");return -1;}//以创建的形式打开目标文件int dfd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0664);if (dfd == -1){perror("open destfile error");return -1;}int size = lseek(sfd, 0, SEEK_END);//关闭文件close(sfd);close(dfd);return size; //将文件大小返回
}//定义文件拷贝函数
void copy_file(const char *srcfile, const char *destfile, int start, int len)
{//以只读的形式打开源文件int sfd = open(srcfile, O_RDONLY);if (sfd == -1){perror("open srcfile error");return;}//以创建的形式打开目标文件int dfd = open(destfile, O_WRONLY);if (dfd == -1){perror("open destfile error");return;}//移动光标位置lseek(sfd, start, SEEK_SET);lseek(dfd, start, SEEK_SET);//定义搬运工char buf[128] = "";int sum = 0; //记录拷贝的总个数while (1){//从源文件中读取数据int res = read(sfd, buf, sizeof(buf));sum += res; //将读取的个数累加if (res == 0 || sum > len) //表示文件读取结束{write(dfd, buf, res - (sum - len)); //父进程将最后一次拷贝结束break;}//写入到目标文件中write(dfd, buf, res);}//关闭文件close(sfd);close(dfd);
}
void *task(void *arg)
{if (arg == NULL){return NULL;}// 将arg转换为struct TXT指针struct TXT *txt_ptr = (struct TXT *)arg;int len = get_file_len(txt_ptr->a, txt_ptr->b);pid_t pid = fork();if (txt_ptr->key == 0){//线程1拷贝前一半copy_file(txt_ptr->a, txt_ptr->b, 0, len / 2);pthread_exit(NULL);}else if (txt_ptr->key == 1){//线程2拷贝后一半copy_file(txt_ptr->a, txt_ptr->b, len / 2, len - len / 2);pthread_exit(NULL);}else{printf("load error\n");}
}
int main(int argc, char const *argv[])
{//判断是否是三个文件if (argc != 3){write(2, "input file error\n", sizeof("input file error\n"));return -1;}// 使用strdup复制argv中的字符串,因为argv中的字符串是常量char *source = strdup(argv[1]);char *destination = strdup(argv[2]);if (!source || !destination){perror("strdup failed");// 释放之前可能已经分配的内存free(source);free(destination);return -1;}//创建结构体接收字符信息struct TXT txt1 = {source, destination, 0};struct TXT txt2 = {source, destination, 1};//创建两个线程pthread_t tid1, tid2;if (pthread_create(&tid1, NULL, task, &txt1) != 0){printf("thread create error\n");return -1;}if (pthread_create(&tid2, NULL, task, &txt2) != 0){printf("thread create error\n");return -1;}//阻塞等待线程结束pthread_join(tid1, NULL);pthread_join(tid2, NULL);return 0;
}