2014年4月22日 星期二

Linux PIP wirte and read

By the linux implementaion, the WRITE PROCESS can write max data into the PIP is 64Kbytes if there are no process reads(consumes) data from the PIP then the WRITE PROCESS will block in write(), after the READ PROCESS reads(consumes) data more than 4KBytes from PIP then the WRITE PROCESS will wirte data into the PIP again to fill the data consumed by READ  PROCESS, else the WRITE PRCESS still block in wirte() if the READ PROCESS reads(consumes) data less than 4KBytes.


Ex:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>


int main()
{
   pid_t pid;
   int pipfd[2] = {0};


   if(pipe(pipfd) < 0) {
       printf("pipe() ... fail\n");
       exit(0);
   }


   if((pid = fork()) == 0) {
       char *buf = "0123456789";
       int cnt = 1;


       close(pipfd[0]);
       while(1) {
           printf(" Write ==========> PIP: cnt:%d \n", cnt++);
           //write(pipfd[1], buf, strlen(buf));
           write(pipfd[1], buf, 1);
       }


   } else {
       char buf[512];
       int count = 1;


       sleep(30);
       close(pipfd[1]);
       while(1){
           read(pipfd[0], &buf, sizeof(buf));
           printf(" PIP ==========> Read(): cnt:%d \n", count++);
           sleep(1);
       }
   }


   return 0;

}

沒有留言:

張貼留言