#include <stdio.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <errno.h>
ssize_t fd_r=0;
ssize_t fd_w=0;
int fd3=0;
off_t size=0;
sem_t sem;
sem_t sem2;
void* callBack1(void* arg) //void* arg = &info
{
if(sem_wait(&sem)<0)
{
perror("sem_wait");
pthread_exit(NULL);
}
//printf("%ld\n",size);
//修改文件偏移量到开头位置
lseek(fd_r, 0, SEEK_SET);
lseek(fd_w, 0, SEEK_SET);
char c = 0;
printf("%ld\n",size);
for(int i=0; i<size; i++)
{
//printf("1\n");
read(fd_r, &c, 1);
write(fd_w, &c, 1);
//printf("%c",c);
}
if(sem_post(&sem)<0)
{
perror("sem_post");
pthread_exit(NULL);
}
if(sem_post(&sem2)<0)
{
perror("sem_post");
pthread_exit(NULL);
}
pthread_exit(NULL);
}
void* callBack2(void* arg)
{
if(sem_wait(&sem2)<0)
{
perror("sem_wait");
pthread_exit(NULL);
}
lseek(fd_w, 0, SEEK_SET);
printf("%ld\n",size);
char c = '0';
for(int i=0; i<size; i++)
{
if(read(fd_w, &c, 1)<=0)
{
if(errno==0)
{
return NULL;
}
else
{
perror("read");
return NULL;
}
}
// printf("1");
printf("%c",c);
}
if(sem_post(&sem2)<0)
{
perror("sem_post");
pthread_exit(NULL);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(sem_init(&sem,0,1)<0)
{
perror("sem_init");
return -1;
}
if(sem_init(&sem2,0,0)<0)
{
perror("sem_init");
return -1;
}
fd_r = open("./1.c", O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
fd_w = open("./copy.c", O_RDWR|O_CREAT|O_TRUNC, 0664);
if(fd_w < 0)
{
perror("open");
return -1;
}
fd3 = open("./copy.c",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd3 < 0)
{
perror("open");
return -1;
}
//计算文件大小
size = lseek(fd_r, 0, SEEK_END);
//printf("%ld\n",size);
pthread_t tid1, tid2;
if(pthread_create(&tid1, NULL, callBack1, NULL) != 0){
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2, NULL, callBack2, NULL) != 0){
perror("pthread_create");
return -1;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
//close(fd_r);
//close(fd_w);
//pthread_mutex_destroy(&mutex);
return 0;
}
用信号量的方式,创建两个线程 A B1. A线程读取文件中的内容2. B线程打印A读取到的内容到终端,3. 全部打印完毕后,结束进程;4. 现象类似cat一个文件
最新推荐文章于 2025-04-10 16:10:39 发布