标准IO函数时候讲解的时钟代码,要求输入quit字符串后,结束进程

#include<stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
void* callBack(void* arg)
{
	while(1)
	{
		time_t now=time(NULL);
		struct tm *p =localtime(&now);
		fprintf(stderr,"%4d-%02d-%02d %02d-%02d-%02d\r",\
				p->tm_year+1900,p->tm_mon+1,p->tm_mday,\
				p->tm_hour,p->tm_min,p->tm_sec);

	}
}
int main(int argc, const char *argv[])
{
	pthread_t tid;
	if(pthread_create(&tid,NULL,callBack,NULL)!=0)
	{
		fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
		return -1;
	}
	char str[10]="";
	scanf("%s",str);

	if(strcmp(str,"quit") == 0)
	{
		exit(0);
	}

	return 0;
}

要求定义一个全局变量char buf= "1234567",创建两个线程,不考虑退出条件。
 

#include<stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
char buf[]="1234567";
void strev(char *p)
{
	int i=0;int len=strlen(p)-1;
	char t;
	for(int i=0;i<len;i++)
	{
	t=*(p+i);*(p+i)=*(p+len);*(p+len)=t;
	len--;
	}
	return;
	
}
void* callBackB(void* arg)
{
	while(1)
	{
		strev(buf);
		sleep(1);
	}
}
int main(int argc,const char *argv[])
{	pthread_t tid;
	if(pthread_create(&tid,NULL,callBackB,NULL)!=0)
	{
		fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
		return -1;
	}
	while(1)
	{
		printf("%s\n",buf);
	sleep(1);
	
	}


	return 0;
}

用线程拷贝图片

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
int dp,dp1;
char c;
off_t size;
pthread_mutex_t  mutex;

void *callBackA(void* arg)
{

	pthread_mutex_lock(&mutex);
	lseek(dp,0,SEEK_SET);
	lseek(dp1,0,SEEK_SET);
	for(int i=0;i<size;i++)
	{
		if(read(dp,&c,1)<0)
		{
			perror("read");
		}
		if(write(dp1,&c,1)<0)
		{
			perror("write");
		}
	}
	pthread_mutex_unlock(&mutex);

	pthread_exit(NULL);

}

void *callBackB(void* arg)
{

	pthread_mutex_lock(&mutex);
	lseek(dp,size,SEEK_SET);
	lseek(dp1,size,SEEK_SET);
	for(int i=0;i<size;i++)
	{
		if(read(dp,&c,1)<0)
		{
			perror("read");

		}
		if(write(dp1,&c,1)<0)
		{
			perror("write");

		}
	}
	pthread_mutex_unlock(&mutex);

	pthread_exit(NULL);

}

int main(int argc, const char *argv[])
{
	dp=open("./op.ing",O_RDONLY);
	dp1=open("./cp.ing",O_RDWR|O_CREAT|O_TRUNC,0664);
	size=lseek(dp,0,SEEK_END)/2;
	pthread_t tid,tid1;
	pthread_mutex_init(&mutex,NULL);
	if(pthread_create(&tid,NULL,callBackA,NULL)<0)
	{
		perror("callBackA");
		return -1;
	}

	pthread_join(tid,NULL);

	if(pthread_create(&tid1,NULL,callBackB,NULL)<0)
	{
		perror("callBackB");
		return -1;
	}

	pthread_join(tid1,NULL);

	close(dp);
	close(dp1);
	pthread_mutex_destroy(&mutex);

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值