Monday, 21 October 2013

pipe

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
#include<string.h>
#define sz 50

pthread_t p,c;
sem_t mut,datachk;
char rbuf[sz];
int fd[2],nw;

void * producer()
  {
    char buf[sz];
    while(1)
      {
        printf("\n\nENTER DATA :  ");
        gets(buf);
        sem_wait(&mut);   
        nw=write(fd[1],buf,strlen(buf));
        printf("\n\n%d BYTE DATA IS WRITTEN.",nw);
        sem_post(&mut);
        sem_post(&datachk);
        sleep(1);
      }
  }

void * consumer()
  {
    int i,nr;
    char rbuf[sz];
    while(1)
      {
    sem_wait(&datachk);
        sem_wait(&mut);
        nr=read(fd[0],rbuf,nw);
        printf("\n\n%d BYTE DATA IS READ.",nr);
        printf("\n\n%s DATA IS READ.",rbuf);
        sem_post(&mut);
        for(i=0;i<sz;i++)
          rbuf[i]=0;
      }
  }

void main()
  {
    int i;
    sem_init(&mut,0,1);
    sem_init(&datachk,0,0);
    if(pipe(fd)==0)
      {
      if(pthread_create(&p,NULL,producer,(void *)&i) !=0)
          printf("\n\nERROR CREATION");       
    if(pthread_create(&c,NULL,consumer,(void *)&i) !=0)
          printf("\n\nERROR CREATION");  
        pthread_join(p,NULL);
        pthread_join(c,NULL);
     }
  }

No comments:

Post a Comment