标准IO函数时候讲解的时钟代码,要求输入quit字符串后,结束进程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
//分支记时间
void* callback(void* arg)
{
time_t t;
struct tm* info =NULL;
while(1)
{
t=time(NULL);
info=localtime(&t);
fprintf(stderr, "%d-%02d-%02d %02d:%02d:%02d\r",\
info->tm_year+1900, info->tm_mon+1,\
info->tm_mday, info->tm_hour, info->tm_min,\
info->tm_sec);
sleep(1);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid;
if(pthread_create(&tid,NULL,callback,NULL)!=0)
{
fprintf(stderr,"pthread_create failed:__%d__",__LINE__);
return -1;
}
sleep(1);
while(1){
char arr[32]="";
scanf("%s",arr);
if(0==strcmp(arr,"quit"))
{
return 0;
}
}
}
要求定义一个全局变量 char buf[] = "1234567",创建两个线程,不考虑退出条件。
A线程循环打印buf字符串,
B线程循环倒置buf字符串,即buf中本来存储1234567,倒置后buf中存储7654321. 不打印!!
倒置不允许使用辅助数组。
要求A线程打印出来的结果只能为 1234567 或者 7654321 不允许出现7634521 7234567
不允许使用sleep函数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
char buf[]="1234567";
void* callback(void* arg)
{
//B线程循环倒置
int i=0,j=strlen(buf)-1;
while(i<j)
{
buf[i]=buf[i]^buf[j];
buf[j]=buf[i]^buf[j];
buf[i]=buf[i]^buf[j];
i++;
j--;
}
pthread_exit(NULL);
}
void* callback1(void* arg)
{
printf("%s\n",buf);
}
int main(int argc, const char *argv[])
{
pthread_t tid,tid1;
while(1)
{
if(pthread_create(&tid,NULL,callback,NULL)!=0)
{
fprintf(stderr,"pthread_create failed:__%d__",__LINE__);
return -1;
}
//A线程循环打印
pthread_join(tid,NULL);
if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
{
fprintf(stderr,"pthread_create1 failed:__%d__",__LINE__);
return -1;
}
//B线程循环打印
pthread_join(tid1,NULL);
}
return 0;
}
要求用两个线程拷贝一张图片。A线程拷贝前半部分,B线程拷贝后半部分,不允许使用sleep函数
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
//要求用两个线程拷贝一张图片。
//A线程拷贝前半部分,B线程拷贝后半部分
//不允许使用sleep函数
off_t len;
void* callback(void* arg)
{
int p =open("./111.png",O_RDONLY);
int q =open("./222.png",O_WRONLY |O_CREAT | O_TRUNC,0664);
//copy上半部分
char c=0;
lseek(p,0,SEEK_SET);
lseek(q,0,SEEK_SET);
for(int i=0;i<len/2;i++)
{
read(p,&c,1);
write(q,&c,1);
}
// pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//打开
int p =open("./111.png",O_RDONLY);
if(p<0)
{
perror("open");
return -1;
}
int q =open("./222.png",O_WRONLY |O_CREAT | O_TRUNC,0664);
if(q<0)
{
perror("open");
return -1;
}
//创建
pthread_t tid;
if(pthread_create(&tid,NULL,callback,NULL)!=0)
{
printf("failed__%d__",__LINE__);
return -1;
}
len=lseek(p,0,SEEK_END);
// void* ptr=NULL;
pthread_join(tid,NULL);
//copy下半部分
char c=0;
lseek(p,len/2,SEEK_SET);
lseek(q,len/2,SEEK_SET);
for(int i=len/2;i<len;i++)
{
read(p,&c,1);
write(q,&c,1);
}
close(p);
close(q);
return 0;
}