随笔-167  评论-8  文章-0  trackbacks-0
pipe(建立管道)

表头文件 #include<unistd.h>
定义函数 int pipe(int filedes[2]);
函数说明
    pipe()会建立管道,并将文件描述词由参数 filedes 数组返回。
    filedes[0]为管道里的读取端,所以pipe用read调用的
    filedes[1]则为管道的写入端。
    
返回值:  若成功则返回零,否则返回-1,错误原因存于 errno 中。
错误代码:
    EMFILE 进程已用完文件描述词最大量
    ENFILE 系统已无文件描述词可用。
    EFAULT 参数 filedes 数组地址不合法。

#include <unistd.h>
#include <stdio.h>

int main( void )
{
    int filedes[2];
    char buf[80];
    pid_t pid;
   
    pipe( filedes );
   
    if ( (pid=fork()) > 0 )
    {
        printf( "This is in the father process,here write a string to the pipe.\n" );
        char s[] = "Hello world , this is write by pipe.\n";
        write( filedes[1], s, sizeof(s) );
        close( filedes[0] );
        close( filedes[1] );
    }
    else
    {
        printf( "This is in the child process,here read a string from the pipe.\n" );
        read( filedes[0], buf, sizeof(buf) );
        printf( "%s\n", buf );
        close( filedes[0] );
        close( filedes[1] );
    }
   
    waitpid( pid, NULL, 0 );
   
    return 0;
}


[root@localhost src]# gcc pipe.c
[root@localhost src]# ./a.out
This is in the child process,here read a string from the pipe.
This is in the father process,here write a string to the pipe.
Hello world , this is write by pipe.
posted on 2010-06-14 18:19 老马驿站 阅读(2716) 评论(0)  编辑 收藏 引用 所属分类: c++linux