pipe02.c

来自「嵌入式Linux程序设计与应用案例 电子书源码 中国电力出版社」· C语言 代码 · 共 64 行

C
64
字号
/************
// name : pipe02.c
// author : pyy
// date : 2007-11-23
**************/

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<limits.h>

int main()
{
    int fd[2];
    int fdin;
    char buf[PIPE_BUF];	
    int pid,len;
    // building PIPE
    if((pipe(fd))<0)
    {
        perror("pipe error");
        exit(1);	
    }	
    // building child process
    pid = fork();
    if(pid < 0)
    {
        perror("fork error"); exit(1);	
    }
    // child process  first close write terminal of  pipe  and then read  
    if(pid == 0)
    {
        close(fd[1]);
        while((len = read(fd[0],buf,PIPE_BUF))>0)
        {
            buf[len]='\0';
            printf("Read %d bytes ...\n",len);
            printf("%s\n",buf);	
        }	
        close(fd[0]);
    }
    // father process ,first close read terminal of pipe and then write
    if(pid > 0)
    {
        close(fd[0]);
        fdin = open("pipe01.c",O_RDONLY);	
    	if(fdin < 0)
    	{
    	    perror("open error");exit(1);
    	}
    
    
    while((len = read(fdin,buf,PIPE_BUF))>0) 
             write(fd[1],buf,len);
    close(fdin);
    close(fd[1]);
    }

    // clear zombie process
    waitpid(pid,NULL,0);
    exit(0);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?