IO线程进程 2-28

文章展示了三个C语言的多线程程序实例。第一个程序创建一个线程持续显示当前时间,直到用户输入quit退出。第二个程序通过两个线程实现字符串的不断反转和打印。第三个程序则使用线程进行文件内容的复制,将源文件的前半部分和后半部分分别由不同线程处理。

 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;
}

结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值