开心过好每天!
2013年(23)
分类: LINUX
2013-08-05 18:49:44
#include
#include
#include
#include
#include
#include
#include
sem_t semR,semW;
//封装PV操作
void p(sem_t *psem)
{
if(sem_wait(psem) < 0)
{
perror("fail to sem_wait");
exit(EXIT_FAILURE);
}
}
void v(sem_t *psem)
{
if(sem_post(psem) < 0)
{
perror("fail to sem_post");
exit(EXIT_FAILURE);
}
}
void *threadWrite(void *vptr)
{
char buf[128] = {'\0'};
static int count = 0;
printf("write thread is running\n");
while(1)
{
p(&semW);
fgets(buf,sizeof(buf) - 1,stdin);
buf[strlen(buf) - 1] = '\0';
write(*(int *)vptr,buf,strlen(buf));
printf("write %d byte\n",strlen(buf));
count += strlen(buf);
v(&semR);
if(count >= 127)
goto finish;
}
finish:pthread_exit("write thread is over");
return;
}
void *threadRead(void *vptr)
{
char buf[128] = {'\0'};
int lenth = 0;
printf("thread Read is running\n");
while(1)
{
p(&semR);
lseek(*(int *)vptr,SEEK_SET,0);
read(*(int *)vptr,buf,sizeof(buf) - 1);
buf[strlen(buf)] = '\0';
printf("read %d byte:%s\n",strlen(buf),buf);
if(strlen(buf) >= 127)
goto finish;
v(&semW);
}
finish:pthread_exit("threadRead is over");
return;
}
int main(int argc,char *argv[])
{
int fd;
int retRead = 0,retWrite = 0;;
pthread_t tidRead = 0,tidWrite = 0;
void *resultOfRead = NULL,*resultOfWrite = NULL;
//信号量初始化
sem_init(&semR,0,0);
sem_init(&semW,0,1);
fd = open(argv[1],O_RDWR | O_CREAT | O_TRUNC,0666);
if(fd < 0)
{
fprintf(stderr,"fail to open %s:%s\n",argv[1],strerror(errno));
exit(EXIT_FAILURE);
}
retRead = pthread_create(&tidRead,NULL,threadRead,(void *)&fd);
if(retRead != 0)
{
perror("fail to pthread_create read");
exit(EXIT_FAILURE);
}
retWrite = pthread_create(&tidWrite,NULL,threadWrite,(void *)&fd);
if(retWrite != 0)
{
perror("fail to pthread_create write");
exit(EXIT_FAILURE);
}
pthread_join(tidRead,&resultOfRead);
printf("result of writeTread:%s\n",(char *)resultOfRead);
pthread_join(tidWrite,&resultOfWrite);
printf("resut of readThread:%s\n",(char *)resultOfWrite);
exit(EXIT_SUCCESS);
}