分类: LINUX
2008-08-20 18:17:40
#include intpthread_create(pthread_t*thread,pthread_attr_t*attr, void*(*start_routine)(void*),void*arg); voidpthread_exit(void*retval); intpthread_join(pthread*thread,void**thread_return);
#include #include #include #include #include #include #include #include #include #include #include #defineBUFFER512 structcopy_file{ intinfile; intoutfile; }; void*copy(void*arg) { intinfile,outfile; intbytes_read,bytes_write,*bytes_copy_p; charbuffer[BUFFER],*buffer_p; structcopy_file*file=(structcopy_file*)arg; infile=file->infile; outfile=file->outfile; /*因为线程退出时,所有的变量空间都要被释放,所以我们只好自己分配内存了*/ if((bytes_copy_p=(int*)malloc(sizeof(int)))==NULL)pthread_exit(NULL); bytes_read=bytes_write=0; *bytes_copy_p=0; while((bytes_read=read(infile,buffer,BUFFER))!=0) { if((bytes_read==-1)&&(errno!=EINTR))break; elseif(bytes_read>0) { buffer_p=buffer; while((bytes_write=write(outfile,buffer_p,bytes_read))!=0) { if((bytes_write==-1)&&(errno!=EINTR))break; elseif(bytes_write==bytes_read)break; elseif(bytes_write>0) { buffer_p =bytes_write; bytes_read-=bytes_write; } } if(bytes_write==-1)break; *bytes_copy_p =bytes_read; } } close(infile); close(outfile); pthread_exit(bytes_copy_p); } intmain(intargc,char**argv) { pthread_t*thread; structcopy_file*file; intbyte_copy,*byte_copy_p,num,i,j; charfilename[BUFFER]; structdirent**namelist; structstatfilestat; /*得到当前路径下面所有的文件(包含目录)的个数*/ if((num=scandir(".",&namelist,0,alphasort))<0) { fprintf(stderr,"GetFileNumError:%s\n\a",strerror(errno)); exit(1); } /*给线程分配空间,其实没有必要这么多的*/ if(((thread=(pthread_t*)malloc(sizeof(pthread_t)*num))==NULL)|| ((file=(structcopy_file*)malloc(sizeof(structcopy_file)*num))==NULL) ) { fprintf(stderr,"OutOfMemory!\n\a"); exit(1); } for(i=0,j=0;i d_name); if(stat(filename,&filestat)==-1) { fprintf(stderr,"GetFileInformation:%s\n\a",strerror(errno)); exit(1); } /*我们忽略目录*/ if(!S_ISREG(filestat.st_mode))continue; if((file[j].infile=open(filename,O_RDONLY))<0) { fprintf(stderr,"Open%sError:%s\n\a",filename,strerror(errno)); continue; } strcat(filename,".bak"); if((file[j].outfile=open(filename,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR)) <0) { fprintf(stderr,"Creat%sError:%s\n\a",filename,strerror(errno )); continue; } /*创建线程,进行文件拷贝*/ if(pthread_create(&thread[j],NULL,copy,(void*)&file[j])!=0) fprintf(stderr,"CreateThread[%d]Error:%s\n\a",i,strerror(errno)); j ; } byte_copy=0; for(i=0;i