1、
代码
#include <stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<time.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<pthread.h>
char buf[20]="";
time_t info;
struct tm *t=NULL;
void *call(void *arg)
{
while(1)
{
time(&info);
t=localtime(&info);
printf("%02d-%02d-%02d %02d:%02d:%02d\n",t->tm_year+1900,t->tm_mon+1,t->tm_mday,\
t->tm_hour,t->tm_min,t->tm_sec);
sleep(1);
}
}
int main(int argc, const char *argv[])
{
char str[20]="";
pthread_t tid;
if(pthread_create(&tid,NULL,call,NULL)!=0)
{
printf("create failed\n");
}
while(1)
{
scanf("%s",str);
if(strcmp(str,"quit")==0)
{
exit(0);
}
}
return 0;
}
结果
2、
代码
#include <stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
char buf[]="1234567";
int flag=0;
void *B(void *arg)
{
while(1)
{ char c;
char *p=buf;
char *q=p+strlen(p)-1;
while(p<q)
{
c=*p;
*p=*q;
*q=c;
p++;q--;
}
}
return NULL;
}
void *A(void *arg)
{
while(1)
{
printf("%s\n",buf);
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t tid;
pthread_t ttid;
if(pthread_create(&tid,NULL,A,NULL) != 0||pthread_create(&ttid,NULL,B,NULL)!=0)
{
printf("pthread_create failed\n");
return -1;
}
pthread_join(ttid,NULL);
while(1)
{
}
return 0;
}
结果
3、
代码
#include <stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<fcntl.h>
int fd=0,fp=0;
off_t n=0;
off_t flag=0;
void *copy1(void *arg)
{
char c=0;
lseek(fd,0,SEEK_SET);
lseek(fp,0,SEEK_SET);
for(int i=0;i<n/2;i++)
{
read(fd,&c,1);
write(fp,&c,1);
}
printf("前半部分打印完毕\n");
pthread_exit(NULL);
return NULL;
}
int main(int argc, const char *argv[])
{
umask(2);
fd=open("../图片/1.png",O_RDONLY);
fp=open("./2.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
n=lseek(fd,0,SEEK_END);
flag=n%2;
lseek(fd,0,SEEK_SET);
if(fd<0||fp<0)
{
perror("open");
return -1;
}
pthread_t tid;
if(pthread_create(&tid,NULL,copy1,NULL) != 0)
{
printf("pthread_create failed\n");
return -1;
}
pthread_join(tid,NULL);
printf("%d\n",pthread_join(tid,NULL));
int i=0;
char d=0;
lseek(fd,n/2,SEEK_SET);
lseek(fp,n/2,SEEK_SET);
for(;i<n/2+flag;i++)
{
read(fd,&d,1);
write(fp,&d,1);
}
printf("后半部分打印完毕\n");
close(fd);
close(fp);
return 0;
}
结果