linux无名管道

2018-07-13  本文已影响0人  嵌入式工作
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#if 0
int pipe(int pipefd[2]);

       #define _GNU_SOURCE             /* See feature_test_macros(7) */
       #include <unistd.h>

       int pipe2(int pipefd[2], int flags);

DESCRIPTION
       pipe()  creates  a pipe, a unidirectional data channel that can be used
       for interprocess communication.  The array pipefd is used to return two
       file  descriptors  referring to the ends of the pipe.  pipefd[0] refers
       to the read end of the pipe.  pipefd[1] refers to the write end of  the
       pipe.   Data  written  to  the write end of the pipe is buffered by the
       kernel until it is read from the read end of  the  pipe.   For  further
       details, see pipe(7).
#endif

int main(int argc ,char*argv[])
{
    int buf[1024];
    int  len;
    int pip[2],rc,c;
    int *readfd;
    int *writefd;
    readfd=&pip[0];
    writefd=&pip[1];
    
    rc = pipe(pip);
    printf("start\n");
    if(rc == -1)
    {
        printf("\ncreat pipe fail \n");
        
    }
    
    rc = fork();
    switch(rc)
    {
       case -1:
        printf("fork err \n");
        exit(1);
        case 0:
        close(*readfd);
        while( (c =getchar())>0)
        {
            write(*writefd,&c,1);
        }
        
        break;
        default:
        close(*writefd);
         while(read(*readfd,&c,1)>0)
        {
              putchar(c);
        }
        break;
        
        
    }
    
    
    
}


上一篇 下一篇

猜你喜欢

热点阅读