今日任务
1.代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>/** function: 复制图片* @param [ in] * @param [out] * @return */
int rean_write_file(char *readfile,char *writefile,int start,int len){//readfileint fo=open(readfile,O_RDONLY);if(fo==-1){perror("readfile open");return -1;}int fo2=open(writefile,O_WRONLY);if(fo2==-1){perror("writefile open");return -1;}//移动光标lseek(fo,start,SEEK_SET);lseek(fo2,start,SEEK_SET);int c[1024]={0};int count=0;while(1){int res=read(fo,c,sizeof(128));count+=res;if(count>=len){write(fo2,c,res-(count-len));break;}write(fo2,c,res);}close(fo);close(fo2);return 0;}
/** function: 子进程函数* @param [ in] * @param [out] * @return */
void * fun(void * arg){puts("th1 start...");int size=*(int *)arg;rean_write_file("./bulaien.png","./copy.png",size/2,size-size/2);pthread_exit(NULL);puts("th1 end ...");
}
int main(int argc, const char *argv[])
{int read=open("./bulaien.png",O_RDONLY);int size=lseek(read,0,SEEK_END);close(read);int dest=open("./copy.png",O_WRONLY|O_CREAT|O_TRUNC,0664);if(dest==-1){puts("dest open failed");return -1;}close(dest);//创建新线程pthread_t pth;if(pthread_create(&pth,NULL,fun,&size)==-1){fprintf(stdout,"create thread failed %d",__LINE__);}//主线程puts("main start...");rean_write_file("./bulaien.png","./copy.png",0,size/2);pthread_join(pth,NULL);puts("main end...");puts("copy success");return 0;
}
运行结果:
2.代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>char buf[]="1234567";
/** function: a线程打印,b线程逆置* @param [ in] * @param [out] * @return */
void* inversion(void *argc){//逆置char *str=(char*)argc;while(1)for(int i=0;i<=strlen(str)/2;i++){char tem=*(str+i);*(str+i)=*(str+strlen(str)-1-i);*(str+strlen(str)-1-i)=tem;}
}
int main(int argc, const char *argv[])
{//inversion(buf);//printf("%s\n",buf);pthread_t pth;if(pthread_create(&pth,NULL,inversion,buf)!=0){fprintf(stderr,"create thread failed\n");return -1;}//a进程打印while(1)if(strcmp(buf,"1234567")==0||strcmp(buf,"7654321")==0 )puts(buf);return 0;
}
运行结果:
异常结果:
可能原因我猜是b线程逆置完之后a线程满足条件开始打印,在这期间b线程又进行下一次的逆置,刚好在这时a线程打印了。可能是这样吧。
今日思维导图
想好好睡一觉