- #include <stdio.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <pthread.h>
- #include <semaphore.h>
- #include <string.h>
- #define MAX 100000
- char c[MAX]="";
- struct file
- {
- int fd;
- int size;
- };
- sem_t sem;
- void *callback1(void* arg)
- {
- int i=0;
- lseek(((struct file*)arg)->fd, 0,SEEK_SET);
- for(i=0;i<((struct file*)arg)->size;i++)
- {
- sem_wait(&sem);
- ssize_t p;
- p=read(((struct file *)arg)->fd,&c[i],1);
- printf("%c",c[i]);
- sem_post(&sem);
- }
-
- }
- void *callback2(void* arg)
- {
- if(strlen(c))
- {
- int i=0;
- for(i=0;i<((struct file*)arg)->size;i++)
- {
- sem_wait(&sem);
- printf("%c",c[i]);
- sem_post(&sem);
- }
- }
- pthread_exit(NULL);
- }
-
- int main(int argc, const char *argv[])
- {
- if(sem_init(&sem,0,1)!=0)
- {
- printf("申请失败");
- return -1;
- }
- int fd=open(argv[1],O_RDONLY);
- off_t size=lseek(fd,0,SEEK_END);
- printf("size%ld",size);
- if(fd<0)
- {
- perror("open");
- }
- struct file p;
- p.fd=fd;
- p.size=size;
- pthread_t sid1;
- if(pthread_create(&sid1,NULL,callback1,(void*)&p)!=0)
- {
- perror("pthread_create");
- return -1;
- }
- pthread_t sid2;
- if(pthread_create(&sid2,NULL,callback2,(void*)&p)!=0)
- {
- perror("pthread_create");
- return -1;
- }
- pthread_join(sid1,NULL);
- pthread_join(sid2,NULL);
- sem_destroy(&sem);
- close(fd);
- return 0;
- }