IO和进程day05(进程与线程)

今日任务

IO和进程day05(进程与线程)_第1张图片

1.代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

/*
 * function:    复制图片
 * @param [ in] 
 * @param [out] 
 * @return      
 */
int rean_write_file(char *readfile,char *writefile,int start,int len){
	//readfile
	int 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;
}

运行结果:

IO和进程day05(进程与线程)_第2张图片

2.代码

#include 
#include 
#include 
#include 

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

运行结果:

IO和进程day05(进程与线程)_第3张图片

异常结果:

IO和进程day05(进程与线程)_第4张图片

可能原因我猜是b线程逆置完之后a线程满足条件开始打印,在这期间b线程又进行下一次的逆置,刚好在这时a线程打印了。可能是这样吧。

今日思维导图

想好好睡一觉

你可能感兴趣的:(c语言)